using Godot;
using System.Collections.Generic;

/**
 * Script attached to the main node in the ExperienceInput scene.
 */
public partial class ExperienceInput : HBoxContainer
{
	[Export]
	public Texture2D starTexture;
	[Export]
	public Texture2D starSelectedTexture;

	[Export]
	public TextureButton starButton0;
	[Export]
	public TextureButton starButton1;
	[Export]
	public TextureButton starButton2;
	[Export]
	public TextureButton starButton3;
	[Export]
	public TextureButton starButton4;

	private List<TextureButton> stars;
	private int index = -1;

	[Signal]
	public delegate void ExperienceChangedEventHandler(int value);

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

		for (int i = 0; i < stars.Count; i++)
		{
			int starIndex = i; // Use local variable
			stars[i].Pressed += () => { OnStarButtonPressed(starIndex); };
		}

		Update();
	}

	/**
	 * The experience level, from 0 (no star selected) to 5.
	 */
	public int Experience
	{
		get => index + 1;

		set
		{
			index = value - 1;

			Update();
		}
	}

	private void OnStarButtonPressed(int starIndex)
	{
		// Clicking a star which is already selected turns it off, together with the stars following it
		bool isSelected = starIndex <= index;

		Experience = isSelected ? starIndex : starIndex + 1;

		// Emit signal
		EmitSignal(SignalName.ExperienceChanged, Experience);
	}

	/**
	 * Highlight the stars up to the current experience level.
	 * The selected state is applied to the buttons' normal texture, so that all the stars
	 * are repainted at once and the buttons' own pressed state never shows through.
	 */
	private void Update()
	{
		for (int i = 0; i < stars.Count; i++)
			stars[i].TextureNormal = i <= index ? starSelectedTexture : starTexture;
	}
}
