using System;
using UnityEngine;
using UnityEngine.Events;

namespace MPStudio
{
    public class HpCtrl : MonoBehaviour
    {
        public bool isInvincible = false;

        //如果是物品能减才能减
        public bool isGoods = false;
        
        public UnityEvent<int> dieEvent;

        public int maxHp;
        public int curHp;
        public bool isDie;

        protected virtual void Awake()
        {
            
        }

        // Start is called once before the first execution of Update after the MonoBehaviour is created
        protected virtual void Start()
        {
            curHp = maxHp;
            isDie = false;
            dieEvent.AddListener(printCurHp);
        }

        void printCurHp(int val)
        {
            //     Debug.Log("curHp" + val);
        }

        void GoDie()
        {
            ReduceHp(maxHp);
        }

        public float GetRatio()
        {
            return ((float)curHp) / maxHp;
        }

        public virtual void AddHp(int hp)
        {
            if (isDie) return;
            
            curHp += hp;
            if (curHp > maxHp)
            {
                curHp = maxHp;
            }
            
            
        }

        public virtual bool ReduceHp(int val)
        {
            if (isDie) return false;
            if (isInvincible) return false;

            if (isGoods)
            {
                if ((curHp - val) < 0)
                {
                    return false;
                }
            }
            
            //print("reducehp ,and hp is " + val.ToString());
            curHp -= val;

            if (curHp <= 0 && (isDie == false))
            {
                isDie = true;
                dieEvent.Invoke(curHp);
            }

            return true;
        }

    }
}