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

public class Fade : MonoBehaviourSingleton<Fade>
{
    public const float Short = 0.3f;
    public const float Default = 0.6f;
    public const float Long = 1.0f;

    public delegate void FadeCallback();

	private float m_level = 0.0f;	// 0=transparent (faded in) 1=opaque (faded out)
	private float m_speed = 0.0f;
	private FadeCallback m_callback;
	private Image m_image;

    public bool IsFaded()
    {
        return m_level != 0.0f;
    }

    public bool IsFading()
	{
		return m_speed != 0.0f;
	}

	public float GetFade()
	{
		return m_level;
	}

	public void SetFade(float level)
	{
		m_level = level;
		m_speed = 0.0f;
		Apply();
	}

	public void FadeIn(float time, FadeCallback callback = null)
	{
		m_level = 1.0f;
		m_speed = -1.0f / time;
		m_callback = callback;
		Apply();
	}
	
	public void FadeOut(float time, FadeCallback callback = null)
	{
		m_level = 0.0f;
		m_speed = 1.0f / time;
		m_callback = callback;
		Apply();
	}
	

	void Update () 
	{
		if(m_speed != 0)
		{
            m_level += m_speed * Time.unscaledDeltaTime;
            if (m_level > 1.0f)
			{
				m_level = 1;
				m_speed = 0;
				if(m_callback != null)
					m_callback();
			}
			else if(m_level < 0.0f)
			{
				m_level = 0;
				m_speed = 0;
				if(m_callback != null)
					m_callback();
			}

			Apply();
		}
	}
	
	private void Apply()
	{
		if(m_image == null)
			m_image = GetComponent<Image>();

		if(m_level > 0.0f)
		{
			m_image.enabled = true;
			m_image.color = new Color(0.0f, 0.0f, 0.0f, m_level);
		}
		else
		{
			m_image.enabled = false;
		}
	}
	
}
