using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class script : MonoBehaviour
{
    [SerializeField] private MusicManager musicManager;
    [SerializeField] private Image numberOutlineObject;
    [SerializeField] private Image numberFillObject;
    public PlayerCombat playerCombat;
    public Health playerHealth;
    
    [Header("Number Assets")]
    [SerializeField] private Sprite[] numberOutlineSprites;
    [SerializeField] private Sprite[] numberFillSprites;
    
    private float _fillAmount; // from 0 to 1
    private int _numberIdx; // from 0 to 9
    

    private void Start()
    {
        _numberIdx = PlayerPrefs.GetInt("numberIdx", 0);
        _fillAmount = PlayerPrefs.GetFloat("fillAmount", 0f);
        numberOutlineObject.sprite = numberOutlineSprites[_numberIdx];
        numberFillObject.sprite = numberFillSprites[_numberIdx];
    }

    private void OnEnable()
    {
        playerCombat.OnScoreIncreased += IncreaseScore;
        playerHealth.OnScoreDecreased += DecreaseScore;
    }

    private void OnDisable()
    {
        playerCombat.OnScoreIncreased -= IncreaseScore;
        playerHealth.OnScoreDecreased -= DecreaseScore;
    }
    
    
    private void IncreaseScore()
    {
        _fillAmount += 0.1f;
        if (_fillAmount >= 1)
        {
            musicManager.PlayGoodMusic();
            if (_numberIdx == 9)
            {
                _fillAmount = 1.0f;
                return;
            }
            _numberIdx++;
            numberOutlineObject.sprite = numberOutlineSprites[_numberIdx];
            numberFillObject.sprite = numberFillSprites[_numberIdx];
            _fillAmount = 0.1f;
        }
        numberFillObject.fillAmount = _fillAmount;
        
        PlayerPrefs.SetInt("numberIdx", _numberIdx);
        PlayerPrefs.SetFloat("fillAmount", _fillAmount);
        PlayerPrefs.Save();
    }
    
    private void DecreaseScore()
    {
        _fillAmount -= 0.1f;
        if (_fillAmount < 0)
        {
            musicManager.PlayBadMusic();
            if (_numberIdx == 0)
            {
                _fillAmount = 0.0f;
                return;
            }
            _numberIdx--;
            numberOutlineObject.sprite = numberOutlineSprites[_numberIdx];
            numberFillObject.sprite = numberFillSprites[_numberIdx];
            _fillAmount = 0.8f;
        }
        numberFillObject.fillAmount = _fillAmount;
        
        PlayerPrefs.SetInt("numberIdx", _numberIdx);
        PlayerPrefs.SetFloat("fillAmount", _fillAmount);
        PlayerPrefs.Save();
    }
}
