using System;
using RebootKit.Engine.Foundation;
using UnityEngine;
using UnityEngine.InputSystem;

namespace RebootKit.Engine.Development {
    static class DebugCVars {
        [ConfigVar("debug.overlay", 0, "Controls overlay visibility. 0 - hidden, 1 - visible")]
        public static ConfigVar OverlayMode;

        [ConfigVar("debug.game_version", 1, "Controls game version overlay visibility. 0 - hidden, 1 - visible")]
        public static ConfigVar ShowGameVersion;
    }

    public class DevToolsService : ServiceMonoBehaviour {
        [SerializeField] DebugOverlayView m_DebugOverlayView;
        [SerializeField] GameVersionOverlay m_GameVersionOverlay;

        IDisposable m_CVarChangedListener;

        void Start() {
            ConfigVar.StateChanged += OnCVarChanged;
            OnCVarChanged(DebugCVars.OverlayMode);
            OnCVarChanged(DebugCVars.ShowGameVersion);
        }

        void OnDisable() {
            Dispose();
        }

        public override void Dispose() {
            ConfigVar.StateChanged -= OnCVarChanged;
        }

        void Update() {
            if (InputSystem.GetDevice<Keyboard>().f3Key.wasReleasedThisFrame) {
                DebugCVars.OverlayMode.Set(DebugCVars.OverlayMode.IndexValue == 1 ? 0 : 1);
            }
        }

        void OnOverlayModeChanged(int mode) {
            if (mode == 1) {
                m_DebugOverlayView.gameObject.SetActive(true);
            } else {
                m_DebugOverlayView.gameObject.SetActive(false);
            }
        }

        void OnCVarChanged(ConfigVar cvar) {
            if (cvar == DebugCVars.OverlayMode) {
                OnOverlayModeChanged(cvar.IndexValue);
            } else if (cvar == DebugCVars.ShowGameVersion) {
                m_GameVersionOverlay.gameObject.SetActive(cvar.IndexValue > 0);
            }
        }
    }
}