using System.Linq;
using Godot;

namespace Cirno.Scripts.UI;

public partial class KeyRemappingItem : HBoxContainer
{
    public StringName KeyId { get; set; }
    public StringName KeyName { get; set; }

    [Export] public Label NameLabel { get; private set; }
    [Export] public Label InputLabel { get; private set; }

    private bool _active = false;

    public override void _Ready()
    {
        NameLabel.Text = KeyName;
        var actions = InputMap.GetActions();

        var action = actions.FirstOrDefault(x => x == KeyId);
        var events = InputMap.ActionGetEvents(action);

        foreach (var e in events)
        {
            var button = new Button();

            button.Text = e switch
            {
                InputEventKey key => key.PhysicalKeycode.ToString(),
                InputEventJoypadButton jButton => $"Joypad {jButton.ButtonIndex}",
                InputEventMouseButton mouseButton => $"Mouse {mouseButton.ButtonIndex}",
                _ => e.AsText()
            };
            button.Pressed += () => { BeginRemap(button, action, e); };
            this.AddChild(button);
        }


        //InputLabel.Text = string.Join(",", events.Select(x => x.AsText()));
    }

    private void BeginRemap(Button button, StringName action, InputEvent e)
    {
        button.Text = "Remapping...";
        _active = true;
    }

    public void StartRemap()
    {
        _active = true;
    }

    public override void _Input(InputEvent e)
    {
        if (!_active) return;

        if (e is InputEventKey keyEvent && keyEvent.Pressed)
        {
            GD.Print(keyEvent.Keycode);
            //InputLabel.Text = keyEvent.Keycode.ToString();
            
            _active = false;
        }
    }
}