using UnityEngine;
using UnityEngine.UI;
using UnityProgressBar;

public class UIManager : MonoBehaviour
{
    public Player player;

    public Text scoreText;

    public Text bonusText;

    public Text levelText;

    public Text livesText;

    public Text percentCoveredText;

    public Text lasersText;

    public Text magnetsText;

    public Text multiplierText;

    public AudioClip lastLifeWarning;

    public SpriteRenderer lastLifeLabel;

    public ProgressBar progressBar;

    private AudioSource audioSource;

    private float warningTimer = 0f;

    private int Clamp(int value, int min, int max)
    {
        if (value < min)
        {
            value = min;
        }
        else if (value > max)
        {
            value = max;
        }
        return value;
    }

    void Start()
    {
        audioSource = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        scoreText.text = $"{Clamp(player.score, 0, 9999999)}";
        bonusText.text = $"{player.bonus}";
        levelText.text = $"{Clamp(player.level, 1, 99)}";
        percentCoveredText.text = $"{Clamp(player.percentCovered, 0, 100)}";
        lasersText.text = $"{Clamp(player.laserCount, 0, 99)}";
        magnetsText.text = $"{Clamp(player.magnetCount, 0, 99)}";
        progressBar.Value = player.speedBonus;

        if (player.multiplier != 1)
        {
            int multiplierValue = player.multiplier == 0.5f ? 1 : (int)(player.multiplier);
            multiplierText.text = $"{multiplierValue}";
        }
        else
        {
            multiplierText.text = "";
        }

        if (player.lives == 1)
        {
            lastLifeLabel.enabled = true;
            warningTimer += Time.deltaTime;

            if (warningTimer >= 1.0f)
            {
                audioSource.PlayOneShot(lastLifeWarning);
                warningTimer = 0f;
            }
        }
        else
        {
            lastLifeLabel.enabled = false;
            livesText.text = $"{Clamp(player.lives, 0, 99)}";
        }
    }
}
