using UnityEngine;
using UnityEngine.UI;

public enum TransitionType { FadeIn, FadeOut }

public class SceneTransition : MonoBehaviour 
{
    public Image faderImage;
	public float speed = 1.0f;
	public bool triggered;
	public bool runWhenPaused;
	public bool completed;
	public float position = 0.0f;
	private float triggerTime = 0.0f;
	
	void Update() 
	{
		#if PROFILE
		var profiler = SmilingProfiler.GetProfiler("SceneTransition.Update");
		profiler.StartTiming();
		#endif

		if(triggered && !completed)
		{
			if(triggerTime == 0.0f)
			{
				triggerTime = Time.realtimeSinceStartup;
			}
			if(Time.timeScale > 0.0f)
			{
                position = position.AddWithinRange(speed * Time.deltaTime, 0f, 1f);
			}
			else
			{
				if(runWhenPaused && triggerTime > 0.0f)
				{
					position = position.AddWithinRange(speed * (Time.realtimeSinceStartup - triggerTime), 0f, 1f);
				}
			}
			if(position >= 1f && speed > 0f)
			{
				position = 1f;
				completed = true;
			}
            if (position <= 0f && speed < 0f)
            {
                position = 0f;
                completed = true;
            }
        }

        if(position > 0f)
        {
            if (!faderImage.enabled)
            {
                faderImage.enabled = true;
            }
            faderImage.color = new Color(1f, 1f, 1f, position);
        }
        else
        {
            if (faderImage.enabled)
            {
                faderImage.enabled = false;
            }
        }
	
		#if PROFILE
		profiler.StopTiming();
		#endif
	}
	
	public void Clear()
	{
		//position = 0.0f;
		triggered = false;
		completed = false;
		triggerTime = 0.0f;
	}
	
	public void Fade(bool fadeIn, float speed)
	{
        Clear();
		this.speed = speed * (fadeIn ? -1f : 1f);
		triggered = true;
	}
}
