using UnityEngine;
using System.Collections;
using Framework.Entities;
using UnityEngine.UI;
using Framework.Utility;

public class FadeDisplay : CoreBehaviour
{
    public class FadeInAction : CoreAction
    {
        public float time;

        public FadeInAction(float time)
        {
            this.time = time;
        }
    }

    public class FadeOutAction : CoreAction
    {
        public float time;

        public FadeOutAction(float time)
        {
            this.time = time;
        }
    }

    public Image panel;
    private Color color;
    public UnityTimer fadeTimer = new UnityTimer(1f, false);
    private bool fadeIn;
    private bool fadeOut;

    protected override void InnerAwake()
    {
        AddGlobalActionHandler<FadeInAction>(this, FadeIn);
        AddGlobalActionHandler<FadeOutAction>(this, FadeOut);
        panel = GetComponent<Image>();
        color = panel.color;
    }

    protected override void InnerUpdate()
    {
        if (fadeIn && !fadeOut)
        {
            this.fadeTimer.Advance();
            panel.color = new Color(color.r, color.g, color.b, this.fadeTimer.GetCurrent() / this.fadeTimer.GetEnd());
            if (this.fadeTimer.IsComplete())
            {
                this.fadeTimer.Reset();
                fadeIn = false;
            }
        }
        if (fadeOut)
        {
            this.fadeTimer.Advance();
            panel.color = new Color(color.r, color.g, color.b, (1-(this.fadeTimer.GetCurrent() / this.fadeTimer.GetEnd())));
            if (this.fadeTimer.IsComplete())
            {
                this.fadeTimer.Reset();
                fadeOut = false;
            }
        }
    }

    private void FadeIn(FadeInAction action)
    {
        if (!fadeIn && !fadeOut)
        {
            this.fadeTimer.SetEnd(action.time);
            fadeIn = true;
            fadeOut = false;
        }
    }

    private void FadeOut(FadeOutAction action)
    {
        if (!fadeOut)
        {
            this.fadeTimer.SetEnd(action.time);
            fadeOut = true;
            fadeIn = false;
        }
    }
}
