using UnityEngine;
using System.Collections;
using Framework.Entities;
using Framework.Extensions;
using Framework.Utility;
using UnityStandardAssets.ImageEffects;

public class AlchemistDeathHandler : CoreBehaviour
{
    public Transform spawn;
    public AlchemistBag bag;
    public int lives = 3;
    public float slowMotionSpeed = 0.1f;
    public GameObject camera;
    bool dead = false;
    UnityTimer deathTimer = new UnityTimer(0.5f, false);

    protected override void InnerAwake()
    {
        AddGlobalActionHandler<DayDirector.NewDayAction>(this, NewDay);
        AddGlobalActionHandler<Health.DeadAction>(this, HandleDeath);
        bag = GetComponent<AlchemistBag>();
    }

    protected override void InnerUpdate()
    {
        if (dead)
        {
            deathTimer.Advance();
            if (deathTimer.IsComplete())
            {
                //if (this.lives > 0)
                //{
                    this.transform.position = spawn.transform.position + Vector3.up;
                    //this.lives--;
                    bag.medHerbsCount = 0;
                    bag.invDropCount = 0;
                    bag.destroyDustCount = 0;
                    Interact(new Health.ReviveAction());
                    dead = false;
                    deathTimer.Reset();
                    Time.timeScale = 1f;
                    Time.fixedDeltaTime = 0.02f;
                    camera.GetComponent<ColorCorrectionCurves>().enabled = false;
                    Announce(new DayDirector.EndDayAction());
                    Announce(new Journal.AddEntryAction("It took me a whole day to recover from that Watcher attack."));
                //}
                //else
                //{
                //    Application.LoadLevel(0);
                //}
            }
        }
    }

    private void HandleDeath(Health.DeadAction action)
    {
        if (!dead)
        {
            dead = true;
            Time.timeScale = slowMotionSpeed;
            Time.fixedDeltaTime = slowMotionSpeed * 0.02f;
            camera.GetComponent<ColorCorrectionCurves>().enabled = true;
            Announce(new FadeDisplay.FadeInAction(this.deathTimer.GetEnd()));
            Debug.Log("DEAD");
        }
    }

    private void NewDay(DayDirector.NewDayAction action)
    {
        this.transform.position = spawn.transform.position + Vector3.up;
        Interact(new Health.ReviveAction());
    }
}
