using Kryz.CharacterStats.Examples;
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Health : Resource
{
    CharacterStats character;

    public UnityEvent<float> onMaxHealthChanged = new UnityEvent<float>();
    public UnityEvent onDeath = new UnityEvent();

    [HideInInspector]
    public PhotonView photonView;

    private void Awake()
    {
        character = GetComponent<CharacterStats>();
        photonView = GetComponent<PhotonView>();

        baseMaxValue = maxValue;
        baseFlatRegen = flatRegen;

        character.onUpdateStatValues.AddListener(CalculateMaxValueBasedOnStat);
    }

    protected override void Start()
    {
        if (!photonView.IsMine) return;

        base.Start();
    }

    public override void ChangeValue(float value)
    {
        if (!photonView.IsMine) return;
        //Debug.Log("Value to change: " + value);
        currentValue += value;

        currentValue = Mathf.Clamp(currentValue, 0, maxValue);
        if (currentValue == 0)
        {
            //dead;
            onDeath.Invoke();
        }
        //Debug.Log("CurrentHealth: " + currentValue);
        onResourceChanged.Invoke(currentValue);
    }

    [PunRPC]
    public void RPC_ChangeValueHealth(float value)
    {
        if (!photonView.IsMine) return;
        Debug.Log("Received ChangeValue from RPC from someone");
        ChangeValue(value);
    }

    public override float GetMaxValue()
    {
        return base.GetMaxValue();
    }

    public void CalculateMaxValueBasedOnStat()
    {
        maxValue = baseMaxValue + character.Vitality.Value * 10f;

        CalculateRegenValueBasedOnStat();

        onMaxHealthChanged.Invoke(maxValue);
    }
    public void CalculateRegenValueBasedOnStat()
    {
        flatRegen = baseFlatRegen + (character.Strength.Value - character.Strength.BaseValue) * 0.5f;
        percentRegen = (character.Vitality.Value - character.Vitality.BaseValue) * 0.01f;
    }

    public override void SetMaxValue(float value)
    {
        base.SetMaxValue(value);

        onMaxHealthChanged.Invoke(maxValue);
    }


}
