using Godot;

namespace Mr.BrickAdventures.Autoloads;

public partial class InputDeviceManager : Node
{
    public enum InputDevice { Mouse, Keyboard, Gamepad }
    public static InputDeviceManager Instance { get; private set; }

    public InputDevice CurrentDevice { get; private set; } = InputDevice.Mouse;

    public bool IsPointerless => CurrentDevice is InputDevice.Keyboard or InputDevice.Gamepad;

    [Signal] public delegate void DeviceChangedEventHandler(int device);

    public override void _Ready()
    {
        Instance = this;
        Input.MouseMode = Input.MouseModeEnum.Visible;
    }

    public override void _ExitTree()
    {
        if (Instance == this) Instance = null;
    }

    public override void _Input(InputEvent @event)
    {
        InputDevice detected;

        if (@event is InputEventMouseMotion or InputEventMouseButton)
            detected = InputDevice.Mouse;
        else if (@event is InputEventKey)
            detected = InputDevice.Keyboard;
        else if (@event is InputEventJoypadButton)
            detected = InputDevice.Gamepad;
        else if (@event is InputEventJoypadMotion joyEvent)
        {
            if (Mathf.Abs(joyEvent.AxisValue) <= 0.15f) return;
            detected = InputDevice.Gamepad;
        }
        else
            return;

        if (detected == CurrentDevice) return;

        CurrentDevice = detected;
        Input.MouseMode = CurrentDevice == InputDevice.Mouse
            ? Input.MouseModeEnum.Visible
            : Input.MouseModeEnum.Hidden;

        EmitSignal(SignalName.DeviceChanged, (int)CurrentDevice);
    }
}
