using System;
using Autodesk.Navisworks.Api.Plugins;
using NavisworksTransport.UI.WPF.Views;
using NavisworksTransport.Utils;
using System.Windows.Forms.Integration;
using NavisApplication = Autodesk.Navisworks.Api.Application;

namespace NavisworksTransport.Core.AliasTree
{
    [Plugin("NavisworksTransport.AliasTree", "Tian",
        DisplayName = "别名树",
        ToolTip = "自定义节点别名管理面板 — 双击编辑、右键菜单、JSON 导入导出")]
    [DockPanePlugin(300, 400, FixedSize = false, AutoScroll = true)]
    public class AliasTreePlugin : DockPanePlugin
    {
        private AliasTreeControl _control;

        public override System.Windows.Forms.Control CreateControlPane()
        {
            LogManager.Info("[别名树] 创建 DockPane 面板");

            var eh = new ElementHost { AutoSize = true, BackColor = System.Drawing.Color.White };
            _control = new AliasTreeControl();
            _control.OnDatabaseNeeded += TryConnectToDatabase;
            _control.BeforeSaveAlias += EnsureDatabaseCreated;
            eh.Child = _control;
            eh.CreateControl();

            // 面板创建时如果文档已存在，立即连接数据库
            TryConnectToDatabase();

            return eh;
        }

        public override void DestroyControlPane(System.Windows.Forms.Control pane)
        {
            LogManager.Info("[别名树] 销毁 DockPane 面板");

            if (pane is ElementHost eh && eh.Child is AliasTreeControl ctrl)
            {
                ctrl.Cleanup();
                eh.Child = null;
            }

            _control = null;
            pane?.Dispose();
        }

        protected override void OnLoaded()
        {
            base.OnLoaded();
            NavisApplication.ActiveDocumentChanged += OnDocumentChanged;
            // 面板自动恢复时文档可能已加载，主动尝试连接
            TryConnectToDatabase();
        }

        protected override void OnUnloading()
        {
            NavisApplication.ActiveDocumentChanged -= OnDocumentChanged;
            base.OnUnloading();
        }

        private void OnDocumentChanged(object sender, System.EventArgs e)
        {
            TryConnectToDatabase();
        }

        private void TryConnectToDatabase()
        {
            if (_control == null) return;
            if (_control.GetDataStore() != null) return;

            try
            {
                var doc = NavisApplication.ActiveDocument;
                if (doc == null || string.IsNullOrEmpty(doc.FileName)) return;

                // 只连接，不创建（和路径规划一致）
                var pathManager = PathPlanningManager.GetActivePathManager();
                pathManager?.DatabaseInitialize(createIfMissing: false);

                var db = pathManager?.GetPathDatabase();
                if (db?.Connection == null) return;

                var store = new AliasDataStore(db.Connection);
                store.EnsureTableExists();
                _control.SetDataStore(store);
                LogManager.Info("[别名树] 已连接别名数据库");
            }
            catch (Exception ex)
            {
                LogManager.Error($"[别名树] 连接数据库失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 确保数据库已创建（保存别名时调用）
        /// </summary>
        private void EnsureDatabaseCreated()
        {
            if (_control?.GetDataStore() != null) return;
            var pathManager = PathPlanningManager.GetActivePathManager();
            pathManager?.DatabaseInitialize(createIfMissing: true);
            TryConnectToDatabase();
        }
    }
}
