namespace splat;

using Chickensoft.GoDotTest;
using Godot;
using Shouldly;

public class InputManagerTest : TestClass
{
    public InputManagerTest(Node testScene) : base(testScene) { }

    [Test]
    public void ToolChangesOnlyEmitForNewSelection()
    {
        var manager = new InputManager();
        var emissions = 0;
        var selected = InputManager.Tool.Select;
        manager.ToolChanged += tool =>
        {
            emissions++;
            selected = tool;
        };

        manager.SetTool(InputManager.Tool.PlaceRoad);
        manager.SetTool(InputManager.Tool.PlaceRoad);

        manager.CurrentTool.ShouldBe(InputManager.Tool.PlaceRoad);
        selected.ShouldBe(InputManager.Tool.PlaceRoad);
        emissions.ShouldBe(1);
        manager.Free();
    }

    [Test]
    public void ShortcutActionsEmitMenuCancelAndDirectTools()
    {
        var manager = new InputManager();
        manager._Ready();
        var menuRequested = false;
        var cancelRequested = false;
        manager.BuildMenuRequested += () => menuRequested = true;
        manager.CancelRequested += () => cancelRequested = true;

        manager._UnhandledInput(Action("ui_build_menu"));
        manager._UnhandledInput(Action("placement_cancel"));
        menuRequested.ShouldBeTrue();
        cancelRequested.ShouldBeTrue();

        manager._UnhandledInput(Action("ui_demolish"));
        manager.CurrentTool.ShouldBe(InputManager.Tool.Demolish);
        manager._UnhandledInput(Action("ui_inspect"));
        manager.CurrentTool.ShouldBe(InputManager.Tool.Inspect);
        manager.Free();
    }

    [Test]
    public void RegisteringActionsMoreThanOnceDoesNotDuplicateBindings()
    {
        var manager = new InputManager();
        manager._Ready();
        var count = InputMap.ActionGetEvents("placement_confirm").Count;

        manager._Ready();

        InputMap.ActionGetEvents("placement_confirm").Count.ShouldBe(count);
        manager.Free();
    }

    private static InputEventAction Action(string name)
        => new() { Action = name, Pressed = true };
}
