using UnityEngine;
using System.Collections;
using Gamelogic.Grids2;

public class Actor : TurnActor {

    public GridPoint2 Location;
    public bool CanBeAttacked = true;
    public bool IsPlayer = false;
    public bool BlocksLineOfSight = true;
    public bool IsWall = false;
    public bool AllowsHop = true;
    public bool IsSlammable = true;
    public bool IsSplatable = true;
    public bool IsCarryingEgg = false;

    public int HitPoints;
    public int MaxHitPoints;
    public string HurtSoundName;
    public string DeathSoundName;
    //public delegate void RenderDamage();

    public int MeleeDamage;
    public string DEBUG = "";

    private bool dead = false;

    public void TakeDamage(int amount)
    {        
        HitPoints = Mathf.Max(0, HitPoints - amount);
        RenderDamage();
        if (HitPoints <= 0)
            Die();
    }

    private void RenderDamage()
    {
        Render rend = new EmptyRender(0.2f);
        rend.AddTrigger(new RenderTrigger(() => this.SendMessage("Animate", "Hurt", SendMessageOptions.DontRequireReceiver), 0.02f));
        if (HitPoints > 0)
        {
            rend.AddTrigger(new RenderTrigger(() => this.SendMessage("Animate", "Idle", SendMessageOptions.DontRequireReceiver), 0.99f));
            rend.AddTrigger(new RenderTrigger(() => RenderSounds.PlaySound(HurtSoundName), 0.04f));
        }
        RenderPipeline.Render(rend);
    }

    public void Die()
    {
        dead = true;
        GameMap.Cell[Location].RemoveActor();
        gameObject.SendMessage("Died", SendMessageOptions.DontRequireReceiver);

        float deathTime = (IsPlayer) ? 1.5f : 0.02f;
        Render rend = new EmptyRender(deathTime);
        rend.AddTrigger(new RenderTrigger(() => this.SendMessage("Animate", "Hurt", SendMessageOptions.DontRequireReceiver), 0.02f));
        rend.AddTrigger(new RenderTrigger(() => RenderSounds.PlaySound(DeathSoundName), 0.04f));
        rend.AddTrigger(new RenderTrigger(() => RenderDeath(), 0.99f));
        RenderPipeline.Render(rend);
    }

    public bool IsDead()
    {
        return dead;
    }

    public void RenderDeath()
    {
        //Debug.Log(name + " rendering death via Destroy call");
        if (IsPlayer)
        {
            GameController.Instance.LoseGame();
        }
        else
        {
            GameObject.Destroy(gameObject);  // previously was Immediate
        }
    }

    protected override bool ShouldSkip()
    {
        DEBUG = Location.X + " " + Location.Y;
        return dead;
    }

}
