using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace ToadieTechnika.GGJ2018Game
{
    public class TransitionScript : GenericSingleton<TransitionScript>
    {
        public delegate void AfterTransitionDelegate();
        AfterTransitionDelegate m_AfterTransitionEvent;

        [SerializeField]
        Image m_ParentImage;

        [SerializeField]
        Image m_TransitionImage;

        [SerializeField]
        RectTransform m_TransitionImgRect;

        [Space]
        [SerializeField]
        AnimationCurve m_OutCurve;

        [SerializeField]
        AnimationCurve m_InCurve;

        [Space]
        [SerializeField]
        Color[] m_TransitionColors;
        int m_CurrentColorIndex;

        #region Properties
        bool TransitionEnabled
        {
            set
            {
                m_ParentImage.raycastTarget = value;
                m_TransitionImage.enabled = value;
                m_TransitionImgRect.localScale = Vector2.zero;
            }
        }

        public bool isTransitioning
        {
            get { return m_TransitionImage.enabled; }
        }
        #endregion

        void Start()
        {
            TransitionEnabled = false;
        }

        public void TransitionInit(AfterTransitionDelegate _AfterTransitionEvent)
        {
            m_AfterTransitionEvent = _AfterTransitionEvent;
            StartCoroutine("TransitionSequence");
        }

        IEnumerator TransitionSequence()
        {
            TransitionEnabled = true;

            m_TransitionImage.color = m_TransitionColors[m_CurrentColorIndex];
            m_CurrentColorIndex = (int)Mathf.Repeat(m_CurrentColorIndex + 1, m_TransitionColors.Length);

            yield return StartCoroutine(ScaleTransition(true));
            m_AfterTransitionEvent();
            yield return StartCoroutine(ScaleTransition(false));

            TransitionEnabled = false;

            yield return null;
        }

        IEnumerator ScaleTransition(bool _isIn)
        {
            float _CurrentTime = 0;
            float _TargetScale = _isIn ? 1 : 0;

            while (m_TransitionImgRect.localScale.x != _TargetScale)
            {
                yield return new WaitForEndOfFrame();
                _CurrentTime = Mathf.MoveTowards(_CurrentTime, 1, Time.deltaTime);

                float _SetLerp = Mathf.Lerp(m_TransitionImgRect.localScale.x, _TargetScale, _CurrentTime);
                float _SetScale = _isIn ? m_InCurve.Evaluate(_SetLerp) : m_OutCurve.Evaluate(_SetLerp);

                m_TransitionImgRect.localScale = new Vector2(_SetScale, _SetScale);
            }

            yield return new WaitForEndOfFrame();
            m_TransitionImgRect.localScale = new Vector2(_TargetScale, _TargetScale);
        }
    }
}