using System;
using UnityEngine;

public class Entity : MonoBehaviour
{
    public enum Actions
    {
        Attack,
        Defend,
        Item
    }
    
    [Serializable]
    public class Stats
    {
        public int LVL;
        public int HP;
        public int ATK;
        public int DEF;
        public int MP;

        public Stats(int lvl, int hp, int atk, int def, int mp)
        {
            LVL = lvl;
            HP = hp;
            ATK = atk;
            DEF = def;
            MP = mp;
        }
    }

    public string Name;
    public Stats Stat;
    public Animator Anim;
    public bool DebugMode;
    public int HP => _hp;
    public int MP => _mp;
    public InfoMeter Info;
    
    private SpriteRenderer _sr;
    private int _hp;
    private int _mp;
    private static readonly int _dead = Animator.StringToHash("Dead");

    private void Start()
    {
        Anim = GetComponent<Animator>();
        _hp = Stat.HP;
        _mp = Stat.MP;
    }

    public void DecrementHP(int dmg)
    {
        _hp = Mathf.Clamp(_hp - dmg, 0, Stat.HP);
        if (dmg > 0 && Anim != null)
        {
            Anim.Play("Damaged", 0);
            Anim.SetBool(_dead, _hp <= 0);
        }
        if (Info != null)
        {
            Info.UpdateInfo(this);
        }
    }
    
    public void DecrementMP(int cost)
    {
        _mp -= cost;
        if (Info != null)
        {
            Info.UpdateInfo(this);
        }
    }
    
    private void Update()
    {
        #if UNITY_EDITOR
        if (DebugMode)
        {
            if (Input.GetKeyUp(KeyCode.Alpha1))
            {
                SetVisible(true);
                Anim.Play("Idle_a", 0);
            }
            if (Input.GetKeyUp(KeyCode.Alpha2))
            {
                SetVisible(true);
                Anim.Play("Damaged", 0);
                Anim.SetBool(_dead, false);
            }
            if (Input.GetKeyUp(KeyCode.Alpha3))
            {
                SetVisible(true);
                Anim.Play("Damaged", 0);
                Anim.SetBool(_dead, true);
            }
        }
        #endif
    }

    public bool IsDead()
    {
        return _hp <= 0;
    }

    private void SetVisible(bool visible)
    {
        if (_sr == null)
        {
            _sr = GetComponent<SpriteRenderer>();
        }
        _sr.enabled = visible;
    }

    public void DeathAnimationDone()
    {
        SetVisible(false);
        Debug.Log("Dead!");
    }
}
