namespace splat;

using Godot;

/// <summary>
/// Controller-navigable tool palette. Scene data owns layout and focus neighbours;
/// this script only translates button intent into a selected game tool.
/// </summary>
public partial class BuildMenu : Control
{
    [Signal] public delegate void ToolSelectedEventHandler(InputManager.Tool tool);

    private Button _cottageButton = default!;

    public override void _Ready()
    {
        _cottageButton = GetNode<Button>("Panel/Margin/Content/Tools/CottageButton");
        var roadButton = GetNode<Button>("Panel/Margin/Content/Tools/RoadButton");
        var demolishButton = GetNode<Button>("Panel/Margin/Content/Tools/DemolishButton");
        var inspectButton = GetNode<Button>("Panel/Margin/Content/Tools/InspectButton");

        _cottageButton.Pressed += () => SelectTool(InputManager.Tool.PlaceBuilding);
        roadButton.Pressed += () => SelectTool(InputManager.Tool.PlaceRoad);
        demolishButton.Pressed += () => SelectTool(InputManager.Tool.Demolish);
        inspectButton.Pressed += () => SelectTool(InputManager.Tool.Inspect);

        Close();
    }

    public void Toggle()
    {
        if (Visible)
            Close();
        else
            Open();
    }

    public void Open()
    {
        Show();
        _cottageButton.GrabFocus();
    }

    public void Close()
    {
        Hide();
        GetViewport().GuiReleaseFocus();
    }

    private void SelectTool(InputManager.Tool tool)
        => EmitSignal(SignalName.ToolSelected, (int)tool);
}
