using System;
using System.IO;
using Alibabacloud.Rum.Unity.Logs;
using UnityEditor;
using UnityEngine;

namespace Alibabacloud.Rum.Unity.Editor
{
    public class AlibabacloudWindow : EditorWindow
    {
        public static string EditorMenuPath = "Tools -> Alibabacloud";

        protected static string AlibabacloudOptionsAssetName { get; set; } = AlibabacloudOptions.ConfigName;

        private static string OptionsPath =>
            AlibabacloudOptions.GetConfigPath(AlibabacloudOptionsAssetName);

        private IDiagnosticLogger _logger;

        [MenuItem("Tools/Alibabacloud")]
        public static void OnMenuClick()
        {

            Instance = GetWindow<AlibabacloudWindow>();
            Instance.minSize = new Vector2(800, 500);

        }

        public static AlibabacloudWindow? Instance;

        public AlibabacloudOptions Options { get; private set; } = null!; // Set by OnEnable()


        private int _currentTab = 0;

        private readonly string[] _tabs =
        {
            "Core",
            "Logging",
            "Network"
            // "Enrichment",
            // "Transport",
            // "Advanced",
            // "Options Config",
            // "Debug Symbols"
        };

        private void OnEnable()
        {
            SetTitle(this);
            Options = AlibabacloudScriptableObject.CreateOrLoad<AlibabacloudOptions>(
                OptionsPath);
            _logger = new UnityLogger(Options);
        }

        private void OnGUI()
        {
            // Ensure Options and _logger are initialized
            if (Options == null)
            {
                EditorGUILayout.HelpBox("Loading SDK options...", MessageType.Info);
                return;
            }

            if (_logger == null)
            {
                _logger = new UnityLogger(Options);
            }
        
            EditorGUILayout.Space();
            GUILayout.Label("SDK Options", EditorStyles.boldLabel);
        
            Options.Enabled = EditorGUILayout.ToggleLeft(
                new GUIContent("Enable Alibabacloud", "Controls if the SDK should initialize itself or not."),
                Options.Enabled);

            EditorGUILayout.Space();
            EditorGUI.DrawRect(EditorGUILayout.GetControlRect(false, 1), Color.gray);
            EditorGUILayout.Space();

            var selectedTab = GUILayout.Toolbar(_currentTab, _tabs);
            if (selectedTab != _currentTab)
            {
                // Edge-case: Lose focus so currently selected fields don't "bleed" through like DSN -> Override Release
                GUI.FocusControl(null);
                _currentTab = selectedTab;
            }

            EditorGUI.BeginDisabledGroup(!Options.Enabled);

            EditorGUILayout.Space();
            EditorGUI.DrawRect(EditorGUILayout.GetControlRect(false, 1), Color.gray);
            EditorGUILayout.Space();

            switch (_currentTab)
            {
                case 0:
                    CoreTab.Display(Options);
                    break;
                case 1:
                    LoggingTab.Display(Options);
                    break;
                case 2:
                    NetworkTab.Display(Options);
                    break;
            }

            EditorGUI.EndDisabledGroup();
        }

        private void OnLostFocus()
        {
            // Ensure Options is initialized
            if (Options == null)
            {
                return;
            }
        
            // Make sure the actual config asset exists before validating/saving. Crashes the editor otherwise.
            if (!File.Exists(AlibabacloudOptions.GetConfigPath(AlibabacloudOptionsAssetName)))
            {
                _logger?.LogWarning("Options could not been saved. The configuration asset is missing.");
                return;
            }
        
            Validate();
        
            EditorUtility.SetDirty(Options);
            // EditorUtility.SetDirty(CliOptions);
            AssetDatabase.SaveAssets();
        }

        private void Validate()
        {
            if (Options == null || !Options.Enabled)
            {
                return;
            }
        
            ValidateDsn();
        }

        internal void ValidateDsn()
        {
            if (Options == null || string.IsNullOrWhiteSpace(Options.Endpoint))
            {
                return;
            }

            if (Uri.IsWellFormedUriString(Options.Endpoint, UriKind.Absolute))
            {
                return;
            }

            var fullFieldName = $"{nameof(Options)}.{nameof(Options.Endpoint)}";
            // var validationError = new ValidationError(fullFieldName, "Invalid DSN format. Expected a URL.");
            // OnValidationError(validationError);
            //
            // _logger.LogWarning(validationError.ToString());
        }


        internal static void SetTitle(EditorWindow window, string title = "Alibabacloud",
            string description = "Alibabacloud SDK options")
        {
            window.titleContent = new GUIContent(title, null, description);
        }
    }
}