using UnityEngine;
using System.Collections;

namespace mgaia.Utils.LayerSystem
{
    public abstract class BaseLayerSliceEffectFade : LayerSliceEffect
    {
        private float mElapsedTime;
        private IColorContainer[] mColorContainers;
        private Color[] mInitialColors, mFinalColors;
        private Color[] mOriginalInitialColors, mOriginalFinalColors;

        [SerializeField]
        private float _time;

        protected abstract IColorContainer[] GetColorContainers();

        protected override void CustomInit(bool removing)
        {
            mColorContainers = GetColorContainers();

            mInitialColors = new Color[mColorContainers.Length];
            mFinalColors = new Color[mColorContainers.Length];
            mOriginalInitialColors = new Color[mColorContainers.Length];
            mOriginalFinalColors = new Color[mColorContainers.Length];

            for (int i = 0; i < mColorContainers.Length; i++)
            {
                mOriginalInitialColors[i] = new Color(mColorContainers[i].Color.r, mColorContainers[i].Color.g, mColorContainers[i].Color.b, mColorContainers[i].Color.a);
                mOriginalFinalColors[i] = new Color(mColorContainers[i].Color.r, mColorContainers[i].Color.g, mColorContainers[i].Color.b, mColorContainers[i].Color.a);
            }

            mElapsedTime = 0.0f;
            float initialAlpha = removing ? 1.0f : 0.0f;
            for (int i = 0; i < mColorContainers.Length; i++)
            {
                mInitialColors[i] = new Color
                (
                    mOriginalInitialColors[i].r,
                    mOriginalInitialColors[i].g,
                    mOriginalInitialColors[i].b,
                    mOriginalInitialColors[i].a * initialAlpha
                );
                mFinalColors[i] = new Color
                (
                    mOriginalFinalColors[i].r,
                    mOriginalFinalColors[i].g,
                    mOriginalFinalColors[i].b,
                    mOriginalFinalColors[i].a * (1.0f - initialAlpha)
                );
            }
            
            SetColors(0.0f);
        }

        protected override bool CustomUpdate(float deltaTime)
        {
            mElapsedTime += deltaTime;
            if (mElapsedTime >= _time)
            {
                SetColors(1.0f);
                return true;
            }
            else
            {
                float normalizedElapsedTime = mElapsedTime / _time;
                SetColors(normalizedElapsedTime);
                return false;
            }
        }

        private void SetColors(float normalizedElapsedTime)
        {
            for (int i = 0; i < mColorContainers.Length; i++)
            {
                mColorContainers[i].Color = Color.Lerp(mInitialColors[i], mFinalColors[i], normalizedElapsedTime);
            }
        }
    }
}