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

public abstract class ColorPingPongAnim : MonoBehaviour
{

    [SerializeField]
    float period = 1;

    [SerializeField]
    AnimationCurve m_ForwardCurve = AnimationCurve.EaseInOut(0, 0, 1, 1);

    [SerializeField]
    AnimationCurve m_BackwardCurve = AnimationCurve.EaseInOut(0, 0, 1, 1);

    [SerializeField]
    RendererAnim m_RendererAnim;

    [SerializeField]
    Color fromColor = Color.white;

    [SerializeField]
    Color toColor = Color.red;

    protected Action<Color> m_SetColorFunc;
    protected Func<Color> m_GetColorFunc;

    bool m_StopAnim;

    // Use this for initialization
    protected virtual void Awake()
    {
        if (m_RendererAnim == null) m_RendererAnim = gameObject.AddComponent<RendererAnim>();

        Init(fromColor, toColor);
    }

    private void OnEnable()
    {
        Play();
    }
    private void OnDisable()
    {
        Stop();
    }

    public abstract Action<Color> SetColorFunc();
    public abstract Func<Color> GetColorFunc();

    public void Init(Color fromColor, Color toColor)
    {
        this.fromColor = fromColor;
        this.toColor = toColor;
        this.m_SetColorFunc = SetColorFunc();
        this.m_GetColorFunc = GetColorFunc();
    }


    public void Play()
    {
        m_StopAnim = false;
        m_RendererAnim.enabled = true;

        //ResetColor();
        StartCoroutine(PlayForward());
    }

    public void Stop()
    {
        m_StopAnim = true;
        m_RendererAnim.StopAnim();
        m_RendererAnim.enabled = false;
    }

    IEnumerator PlayForward()
    {
        yield return null;
        m_RendererAnim.ColorAnim(m_SetColorFunc, m_GetColorFunc, toColor, period / 2, OnForwardEnd);
    }
    void OnForwardEnd()
    {
        if (m_StopAnim)
            return;

        StartCoroutine(PlayBackward());
    }
    IEnumerator PlayBackward()
    {
        yield return null;
        m_RendererAnim.ColorAnim(m_SetColorFunc, m_GetColorFunc, fromColor, period / 2, OnBackwardEnd);
    }
    void OnBackwardEnd()
    {
        if (m_StopAnim)
            return;

        StartCoroutine(PlayForward());
    }
}