using RebootKit.Engine;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using Logger = RebootKit.Engine.Foundation.Logger;

namespace RebootKit.Editor.RebootWindow {
    static class RTheme {
        public static readonly Color s_FirstColor = ColorFromHex("#B9B8B9");
        public static readonly Color s_SecondColor = ColorFromHex("#6B6B6B");
        public static readonly Color s_BackgroundPrimaryColor = EditorGUIUtility.isProSkin ? ColorFromHex("#1E1E1E") : ColorFromHex("#F0F0F0");
        public static readonly Color s_BackgroundSecondaryColor = ColorFromHex("#242126");
        public static readonly Color s_TextColor = ColorFromHex("#696969");

        static Color ColorFromHex(string hex) {
            if (ColorUtility.TryParseHtmlString(hex, out Color color)) {
                return color;
            } else {
                Debug.LogError($"Failed to parse color from hex: {hex}");
                return Color.white;
            }
        }
    }

    public class RebootEditorWindow : EditorWindow {
        static readonly Logger s_logger = new Logger(nameof(RebootEditorWindow));

        EngineConfigAsset m_EngineConfigAsset;

        VisualElement m_RootElement;
        TabView m_TabView;

        [MenuItem(REditorConsts.k_EditorMenu + "RebootKit")]
        public static void ShowWindow() {
            RebootEditorWindow window = GetWindow<RebootEditorWindow>($"RebootKit - {Application.productName}");
            window.Show();
        }

        void OnEnable() {
            m_EngineConfigAsset = Resources.Load<EngineConfigAsset>(RConsts.k_EngineConfigResourcesPath);
            if (m_EngineConfigAsset == null) {
                EngineConfigAsset newConfig = CreateInstance<EngineConfigAsset>();
                newConfig.name = RConsts.k_EngineConfigAssetName;
                AssetDatabase.CreateAsset(newConfig, RConsts.k_EngineConfigAssetPath);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                s_logger.Info($"Created new engine config asset at: {RConsts.k_EngineConfigAssetPath}");
                
                m_EngineConfigAsset = Resources.Load<EngineConfigAsset>(RConsts.k_EngineConfigResourcesPath);
                if (m_EngineConfigAsset == null) {
                    s_logger.Error($"Couldn't load engine config from resources: {RConsts.k_EngineConfigResourcesPath}");
                    return;
                }
            }

            m_TabView = new TabView();
            m_TabView.AddTab("Home", new HomeView());
            m_TabView.AddTab("Config Vars", new ConfigVarsView());
            m_TabView.AddTab("Game Services", new GameServicesView());
            m_TabView.AddTab("Worlds", new WorldsView());
        }

        void CreateGUI() {
            m_RootElement = rootVisualElement;
            m_RootElement.Clear();

            m_RootElement.Add(m_TabView.Build());
        }
    }
}