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

public class FadeController : MonoBehaviour {
    private Image _image;

    public static FadeController Instance { get; private set; }

    protected void Awake() {
        Instance = this;
        _image = GetComponent<Image>();
    }

    public void FadeIn (float t, bool forceFromBlack = true) {
        _image.gameObject.SetActive(true);
        StopAllCoroutines();
        if (forceFromBlack) {
            _image.color = Color.black;
        }
        StartCoroutine(DoFade(0, t));
    }

    public void FadeOut (float t) {
        _image.gameObject.SetActive(true);
        StopAllCoroutines();
        StartCoroutine(DoFade(1, t));
    }

    private IEnumerator DoFade(float target, float time) {
        Color col = _image.color;
        float startAlpha = col.a;

        for (float t = 0; t < 1; t += Time.deltaTime/time) {
            col.a = Mathf.Lerp(startAlpha, target, t);
            _image.color = col;
            yield return null;
        }
        col.a = target;
        _image.color = col;
        if (Mathf.Approximately(col.a, 0)) {
            _image.gameObject.SetActive(false);
        }
    }
}
