using UnityEngine;
using System.Collections;
using Framework.Entities;
using Framework.Extensions;
using System.Linq;
using System.Collections.Generic;
using Framework.InteractionSystem;
using Framework.Utility;
using Project.Actors;
using Project.World;

namespace Project.Player
{
    public class PlayerDeathHandler : CoreBehaviour
    {
        public class ResetLevelAction : CoreAction {}

        public bool dead = false;
        public float deathHangTime = 2f;

        private UnityTimer deathTimer;
        private PlayerMemory memory;
        private SpriteRenderer renderer;

        // Use this for initialization
        protected override void InnerAwake()
        {
            AddActionHandler<Woundable.DeadAction>(Die);
            ActionMediatorLocator.Get().Subscribe<WorldLoader.FinishedUnloadingAllAction>(this);
            AddActionHandler<WorldLoader.FinishedUnloadingAllAction>(StartDeathTimer);
            this.deathTimer = new UnityTimer(this.deathHangTime, false);
            this.memory = GetComponent<PlayerMemory>();
            this.renderer = this.transform.RecursivelyFindChild("Visual").GetComponent<SpriteRenderer>();
        }

        // Update is called once per frame
        protected override void InnerUpdate()
        {
            if (this.dead)
            {
                this.deathTimer.Advance();
                this.renderer.color = new Color(this.renderer.color.r, this.renderer.color.g, this.renderer.color.b, 1 - (this.deathTimer.GetCurrent() / this.deathTimer.GetEnd()));
            }
            if (this.deathTimer.IsComplete())
            {
                Announce(new ResetLevelAction());
                this.memory.Save();
                Application.LoadLevel(Application.loadedLevel);
            }
        }

        private void Die(Woundable.DeadAction action)
        {
            if (!this.dead)
            {
                Announce(new WorldLoader.UnloadAllAtRandomAction());
                this.dead = true;
            }
        }

        private void StartDeathTimer(WorldLoader.FinishedUnloadingAllAction action)
        {
            //Announce(new ResetLevelAction());
            //this.dead = false;
            
        }
    }
}