using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using GatherAndDefend.Events;
using UnityEngine.UI;

/// <summary>
/// Gère l'affichage des resources
/// </summary>
public class ResourceText : MonoBehaviour
{
    private Color _populationCriticalColor = Color.red;
    private Color _populationWarningColor = Color.yellow;
    private Color _populationRegularColor = Color.white;

    [SerializeField]
    private TextMeshProUGUI _rockText;
    [SerializeField]
    private TextMeshProUGUI _woodText;
    [SerializeField]
    private TextMeshProUGUI _foodText;
    [SerializeField]
    private TextMeshProUGUI _populationText;
    [SerializeField]
    private Image _populationCriticalIndicator;

    private ResourceManager _resourceManager;

    void Start()
    {
        _resourceManager = ResourceManager.Instance;
        _populationCriticalIndicator.enabled = false;
    }

    void Update()
    {
        RefreshResources();
        RefreshPopulation();
    }
    void RefreshResources()
    {
        _rockText.text = _resourceManager.RockAmount.ToString();
        _woodText.text = _resourceManager.WoodAmount.ToString();
        _foodText.text = _resourceManager.FoodAmount.ToString();
    }
    void RefreshPopulation()
    {
        float current = _resourceManager.CurrentPopulation;
        float max = _resourceManager.MaximumPopulation;

        _populationCriticalIndicator.enabled = current >= max;

        var chosenColor = _populationRegularColor; 
        if (current >= max)
        {
            chosenColor = _populationCriticalColor;
            _populationText.fontStyle = FontStyles.Bold;
        }
        else if (((float)current / (float)max) > GlobalConfig.Instance.Current.populationWarningPercentage)
        {
            chosenColor = _populationWarningColor;
            _populationText.fontStyle = FontStyles.Bold;
        }
        else
        {
            _populationText.fontStyle = 0;
        }
        var hexColor = $"#{ToHexString(chosenColor.r)}{ToHexString(chosenColor.g)}{ToHexString(chosenColor.b)}";
        _populationText.text = $"<color={hexColor}>{_resourceManager.CurrentPopulation}</color> / {_resourceManager.MaximumPopulation}";
    }
    string ToHexString(float colorValue) 
    {
        return ((int)(255 * colorValue)).ToString("X2");
    }
}
