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

public class Fader : MonoBehaviour
{
    public bool fadeOutOnStart;
    public float fadeOutDefaultTime = 2f;
    public bool fadeInOnStart;
    public float fadeInDefaultTime = 2f;
    public AnimationCurve curve;
    private CanvasGroup group;
    private Coroutine fadeRoutine;

    private void Awake()
    {
        group = GetComponent<CanvasGroup>();
    }

    private void Start()
    {
        if (fadeOutOnStart)
            Fade(false, fadeOutDefaultTime, false);
        else if (fadeInOnStart)
            Fade(true, fadeInDefaultTime, false);
    }

    public void Fade(bool fadeIn)
    {
        if (fadeRoutine != null)
            StopCoroutine(fadeRoutine);

        float fadeTime = fadeIn ? fadeInDefaultTime : fadeOutDefaultTime;
        bool keepProgress = false;

        fadeRoutine = StartCoroutine(FadeRoutine(fadeIn, fadeTime, keepProgress));
    }

    public void Fade(bool fadeIn, float fadeTime, bool keepProgress)
    {
        if (fadeRoutine != null)
            StopCoroutine(fadeRoutine);

        fadeRoutine = StartCoroutine(FadeRoutine(fadeIn, fadeTime, keepProgress));
    }

    private IEnumerator FadeRoutine(bool fadeIn, float fadeTime, bool keepProgress)
    {
        group.interactable = fadeIn;
        group.blocksRaycasts = fadeIn;

        float startAlpha = fadeIn ? 0f : 1f;
        float endAlpha = fadeIn ? 1f : 0f;

        float progress = 0f;

        if (keepProgress)
            progress = fadeIn ? group.alpha : 1f - group.alpha;

        float time = 0f;
        time += progress * fadeTime;

        while (time < fadeTime)
        {
            float t = time / fadeTime;

            group.alpha = Mathf.Lerp(startAlpha, endAlpha, curve.Evaluate(t));
            time += Time.deltaTime;
            yield return null;
        }

        group.alpha = endAlpha;
        fadeRoutine = null;
    }
}