using UnityEngine;
using UnityEngine.InputSystem;
using NeonTea.Quakeball.Interface;

namespace NeonTea.Quakeball.Util {
    public class PressedActionDisplayer : MonoBehaviour {
        private InputAction Initializer;
        private InputAction AnyAction;

        private InputActionRebindingExtensions.RebindingOperation Rebinding;
        private bool InitializedFromTerminal = false;

        private void Awake() {
            AnyAction = new InputAction("InputAction displayer", binding: "*/*");

            Initializer = new InputAction("Display the next InputAction", binding: "<Keyboard>/f1");
            Initializer.Enable();
            Initializer.performed += _ => {
                InitializedFromTerminal = false;
                StartWaiting();
            };

            Terminal.Singleton.RegisterCommand("read", args => {
                if (args.Length == 0) {
                    InitializedFromTerminal = true;
                    StartWaiting();
                    return true;
                } else {
                    Terminal.Singleton.Println($"<color={Terminal.ERROR_COLOR}>The 'read' command takes no arguments.</color>");
                    return false;
                }
            }, "read - Waits for an input action, and then prints it.");
        }

        private void StartWaiting() {
            if (!InitializedFromTerminal) {
                Debug.Log("Waiting for InputAction to display...");
            } else {
                Terminal.Singleton.Println("Waiting for InputAction to display...");
            }
            Rebinding = AnyAction.PerformInteractiveRebinding().Start();
        }

        private void Update() {
            if (Rebinding != null && Rebinding.completed) {
                string Binding = Rebinding.action.ToString();
                Rebinding.Dispose();
                int Index = Binding.IndexOf("/") + 1;
                Binding = Binding.Substring(Index, Binding.Length - Index - 1);
                if (!InitializedFromTerminal) {
                    Debug.Log("Binding: " + Binding);
                } else {
                    Terminal.Singleton.Println("Binding: " + Binding);
                }
                Rebinding = null;
            }
        }
    }
}
