using UnityEngine;
using System.Collections;

public class Fade : MonoBehaviour
{
    private static Fade s_Instance;
    public static Fade Instance
    {
        get
        {
            if (s_Instance == null)
            {
                s_Instance = GameObject.FindObjectOfType(typeof(Fade)) as Fade;
            }
            return s_Instance;
        }
    }

    public Texture2D m_PatternTexture;
    public Color m_Color;
    public float m_FadeTime = 1f;
    public bool m_PlayOnStart = true;

    private bool m_Opaque;
    private bool m_FireEvent;
    private GameObject m_Target;
    private string m_Action;

	void Start()
    {
        m_Opaque = false;
        m_FireEvent = false;

        if (m_PlayOnStart)
            m_Color.a = 1f;
        else
            m_Color.a = 0f;
	}
	
	void Update()
    {
        if ((m_Color.a <= 0f && !m_Opaque) || (m_Color.a >= 1f && m_Opaque))
        {
            if (m_FireEvent && m_Target != null)
            {
                m_FireEvent = false;
                m_Target.SendMessage(m_Action, SendMessageOptions.DontRequireReceiver);
            }
        }
        else
        {
            if (m_Opaque)
                m_Color.a += Time.deltaTime / m_FadeTime;
            else
                m_Color.a -= Time.deltaTime / m_FadeTime;
        }
	}

    void OnGUI()
    {
        if (m_Color.a <= 0) return;
        GUI.color = m_Color;
        GUI.depth = -9999;
        GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), this.m_PatternTexture, ScaleMode.StretchToFill);
    }

    public void Out()
    {
        Out(null, "");
    }
    public void Out(GameObject target, string action)
    {
        ChangeState(false, target, action);
    }

    public void In()
    {
        In(null, "");
    }
    public void In(GameObject target, string action)
    {
        ChangeState(true, target, action);
    }

    private void ChangeState(bool opaque, GameObject target, string action)
    {
        m_Action = action;
        m_Target = target;
        m_Opaque = opaque;
        m_FireEvent = (target != null && action != "");
    }
}