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

public class StatBar : MonoBehaviour
{
    [SerializeField] Slider slider;
    [SerializeField] Image statImage;
    [SerializeField] StatSO statData;
    [SerializeField] ActionSO statDecrease;

    private float startValue;
    private float tickStep;

    private void Start()
    {
        slider.minValue = statData.StatMin;
        slider.maxValue = statData.StatMax;
        tickStep = statData.TickSteps;
        slider.value = statData.StatMax;
        statImage.color = statData.StatColor;
    }

    private void OnEnable()
    {
        EventManager.Instance.onTick += StatChange;
        statData.Action.onAction += StatIncrease;
        statDecrease.onAction += StatDecrease;
    }

    private void OnDisable()
    {
        EventManager.Instance.onTick -= StatChange;
        statData.Action.onAction -= StatIncrease;
        statDecrease.onAction -= StatDecrease;
        slider.value = statData.StatMax;
        tickStep = statData.TickSteps;
    }

    private void StatChange()
    {
        tickStep--;

        if (tickStep <= 0)
        {
            slider.value--;
            tickStep = statData.TickSteps;
        }

        if (slider.value <= statData.StatMin)
        {
            slider.value = statData.StatMax;
            EventManager.Instance.Stress(statData.NegativeStatImage);
        } 
    }

    private void StatDecrease()
    {
        slider.value--;

        if (slider.value <= statData.StatMin)
        {
            slider.value = statData.StatMax;
            EventManager.Instance.Stress(statData.NegativeStatImage);
        }
    }

    private void StatIncrease()
    {
        float value = slider.value + statData.ClickStatHealAmount;
        slider.value += statData.ClickStatHealAmount;

        Debug.Log("value: "+value);

        if (value > statData.StatMax && statData.OverflowAction != null)
            statData.OverflowAction.InvokeAction();
    }
}