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

/**
 * Script attached to the main node in the ShipMenuOption scene.
 */
public partial class ShipMenuOption : VBoxContainer
{
	/**
	 * Regions of the starship thumbnails in the menu spritesheet.
	 */
	private static readonly Dictionary<string, Rect2> SHIP_REGIONS = new()
	{
		{ "Viking", new Rect2(779, 1, 140, 84) },
		{ "Astro", new Rect2(779, 173, 132, 84) },
		{ "Raptor", new Rect2(779, 87, 135, 84) }
	};

	private static readonly Color SELECTED = new Color(1f, 1f, 1f, 1f);
	private static readonly Color DESELECTED = new Color(1f, 1f, 1f, 0f);

	[ExportCategory("Ship Settings")]

	[Export]
	public string shipName;

	[ExportCategory("UI Settings")]

	[Export]
	public PanelContainer selectionPanel;
	[Export]
	public TextureButton shipButton;
	[Export]
	public Label shipButtonLabel;
	[Export]
	public ProgressBar speedBar;
	[Export]
	public ProgressBar rotationBar;
	[Export]
	public ProgressBar thrustBar;
	[Export]
	public Label weaponNameLabel;

	private Action<string> selectAction;

	public Action<string> SelectAction
	{
		get => selectAction;
		set => selectAction = value;
	}

	public string ShipName => shipName;

	public override void _Ready()
	{
		// Display starship name and thumbnail
		shipButtonLabel.Text = shipName;

		if (SHIP_REGIONS.TryGetValue(shipName, out Rect2 region))
		{
			shipButton.TextureNormal = new AtlasTexture
			{
				Atlas = ResourceLoader.Load<Texture2D>("res://images/spritesheet-menu.png"),
				Region = region
			};
		}

		// Hide selection background
		Deselect();
	}

	public void SetSpeedStat(int current, int max)
	{
		SetStat(speedBar, current, max);
	}

	public void SetRotationStat(int current, int max)
	{
		SetStat(rotationBar, current, max);
	}

	public void SetThrustStat(int current, int max)
	{
		SetStat(thrustBar, current, max);
	}

	public void SetWeaponName(string name)
	{
		weaponNameLabel.Text = name;
	}

	public void Deselect()
	{
		selectionPanel.SelfModulate = DESELECTED;
	}

	public void OnShipButtonClick()
	{
		// Show selection
		selectionPanel.SelfModulate = SELECTED;

		selectAction?.Invoke(shipName);
	}

	private static void SetStat(ProgressBar bar, int current, int max)
	{
		bar.MaxValue = max;
		bar.Value = Math.Min(current, max);
	}
}
