using UnityEngine;
using System.Collections;

namespace mgaia.Utils.LayerSystem
{
	/// <summary>
	/// Monobehaviour que deve ser adicionado a uma LayerSlice para que ela possua algum efeito de entrada na tela (como fade, resize, movimento, etc).
	/// </summary>
    [RequireComponent(typeof(LayerSlice))]
    public abstract class LayerSliceEffect : MonoBehaviour
    {
        private enum EffectUpdatePhases
        {
            WaitingToBegin,
            Playing,
            WaitingToPassToNext
        }

        [SerializeField]
        private float _timeToBegin;

        [SerializeField]
        private float _timeToPassToNext;

        private float mCurrentTime;
        private EffectUpdatePhases mCurrentPhase;
        private bool mRemoving;

        public void Init(bool removing)
        {
            mCurrentTime = 0;
            mRemoving = removing;

            if (removing)
            {
                mCurrentPhase = EffectUpdatePhases.Playing;
            }
            else
            {
                mCurrentPhase = EffectUpdatePhases.WaitingToBegin;
            }

            CustomInit(removing);
        }

        public bool UpdateEffect(float deltaTime)
        {
            if (mRemoving)
            {
                return CustomUpdate(deltaTime);
            }
            else
            {
                if (mCurrentPhase == EffectUpdatePhases.WaitingToBegin || mCurrentPhase == EffectUpdatePhases.WaitingToPassToNext)
                {
                    mCurrentTime += Time.deltaTime;

                    if (mCurrentTime >= (mCurrentPhase == EffectUpdatePhases.WaitingToBegin ? _timeToBegin : _timeToPassToNext))
                    {
                        if (mCurrentPhase == EffectUpdatePhases.WaitingToBegin)
                        {
                            mCurrentPhase = EffectUpdatePhases.Playing;
                        }
                        else if (mCurrentPhase == EffectUpdatePhases.WaitingToPassToNext)
                        {
                            return true;
                        }
                    }

                    return false;
                }
                else if (mCurrentPhase == EffectUpdatePhases.Playing)
                {
                    bool customUpdateResult = CustomUpdate(deltaTime);

                    if (customUpdateResult)
                    {
                        mCurrentPhase = EffectUpdatePhases.WaitingToPassToNext;
                        mCurrentTime = 0;
                    }

                    return false;
                }
            }

            Assert.AssertTrue(false, "Condição não tratada!");
            return true;
        }

        protected abstract void CustomInit(bool removing);

        protected abstract bool CustomUpdate(float deltaTime);

        protected Vector3 mOriginalPosition;

        public void OnLayerPositionSet()
        {
            mOriginalPosition = transform.position;
        }
    }
}