
using Cirno.Scripts.Resources;
using Godot;
using Godot.Collections;

public partial class MusicRoom : MenuBase
{
	[Export]
	public Array<MusicResource> Tracks { get; private set; } = [];

	[Export]
	public ItemList TracksContainer { get; private set; }

	[Export]
	public Texture2D Icon { get; private set; }

	[Export]
	public Label DescriptionLabel { get; private set; }
	
	[Export]
	public Button DefaultSelectedButton { get; private set; }

	private Dictionary<long, AudioNameVisualizer> _tracks = new();

	public override void _Ready()
	{
		DefaultSelectedButton.GrabFocus();
		DescriptionLabel.Text = string.Empty;
		TracksContainer.Clear();
		foreach (var track in Tracks)
		{
			var index = TracksContainer.AddItem($"{track.TrackName} ({track.AuthorName})", Icon);

			var visualizer = new AudioNameVisualizer();
			visualizer.MusicData = track;
			TracksContainer.CallDeferred("add_child", visualizer);

			_tracks.Add((long)index, visualizer);

		}

		TracksContainer.ItemSelected += (long selectedItem) =>
		{
			var vis = _tracks[selectedItem];
			if (vis.MusicData is null) { return; }
			StopAllTracks();
			vis.PlayWithName();
			UpdateDescription(vis.MusicData.Description);
		};
	}

	private void StopAllTracks()
	{
		foreach (var track in _tracks)
		{
			track.Value.Stop();
		}
	}

	private void UpdateDescription(string name)
	{
		DescriptionLabel.Text = name;
	}
}
