using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterHealth : MonoBehaviour {

    [SerializeField]
    protected uint healthAmount = 100;
    public uint HealthAmount { get { return this.healthAmount; } }

    private uint defaultHealth;

    public bool IsAlive { get { return this.healthAmount > 0; } }

    protected Character controller;

    public virtual void PrepareHealth (Character controller) {
        this.controller = controller;

        this.defaultHealth = this.healthAmount;
        this.controller.CharacterAnimator.SetBool(Keys.Animator.DIE_KEY, false);
    }

    public void DealDamage (uint damage) {
        if (healthAmount == 0) {
            return;
        }

        if (damage > this.healthAmount) {
            this.healthAmount = 0;
        } else {
            this.healthAmount -= damage;
        }

        if (!this.IsAlive) {
            this.Die();
        }
    }

    public void Heal (uint heal = 0) {
        if (heal == 0) {
            heal = this.defaultHealth;
        }

        this.healthAmount += heal;

        if (this.IsAlive) {
            this.Recover();
        }
    }

    protected virtual void Die () {
        this.controller.CharacterAnimator.SetBool(Keys.Animator.DIE_KEY, true);

        if (this.controller is Zombie) {
            var ai = this.controller.GetComponent<ZombieAIController>();
            if (ai) {
                ai.ChangeState(new ZombieRecoveryState());
            }

            var gc = GameObject.FindObjectOfType<GameController>();
            if (gc) { 
                gc.GameEvents.CallOnZombieDied();
            }
        }

        if (this.controller is Player) {
            var gc = GameObject.FindObjectOfType<GameController>();
            if (gc) { 
                gc.GameEvents.CallOnPlayerDied();
            }
        }
    }

    protected virtual void Recover () {
        this.controller.CharacterAnimator.SetBool(Keys.Animator.DIE_KEY, false);
    }
}
