using Godot;
using System;
using System.Collections.Generic;

public partial class RankingInput : HBoxContainer
{
    [Export]
    public TextureButton starButton0;
    [Export]
    public TextureButton starButton1;
    [Export]
    public TextureButton starButton2;
    [Export]
    public TextureButton starButton3;
    [Export]
    public TextureButton starButton4;
    [Export]
    private short rank;

    private List<TextureButton> stars;

    [Signal]
    public delegate void RankingChangedEventHandler(short value);

    public override void _Ready()
    {
        stars = [starButton0, starButton1, starButton2, starButton3, starButton4];

        for (int i = 0; i < stars.Count; i++)
        {
            int index = i; // Use local variable
            stars[i].Toggled += isOn => { OnStarButtonToggled(index, isOn); };
        }

        Update();
    }

    public short Rank
    {
        get => rank;

        set
        {
            rank = value;

            Update();
        }
    }

    private void OnStarButtonToggled(int index, bool isOn)
    {
        if (isOn)
            Rank = (short)(index + 1);
        else
            Rank = (short)index;

        // Emit signal
        EmitSignal(SignalName.RankingChanged, rank);
    }
    
    private void Update()
    {
        int index = rank - 1;
        
        for (int i = 0; i < stars.Count; i++)
        {
            var star = stars[i];

            if (!star.ButtonPressed && i <= index)
                star.SetPressedNoSignal(true);

            if (star.ButtonPressed && i > index)
                star.SetPressedNoSignal(false);
        }
    }
}
