using System;
using Autodesk.Navisworks.Api.Plugins;
using NavisworksTransport.Utils;

namespace NavisworksTransport.Commands
{
    [Plugin("TransportRibbonHandler", "NavisworksTransport",
        DisplayName = "物流路径规划工具栏",
        ToolTip = "物流路径规划工具栏命令")]
    [RibbonLayout("TransportRibbon.xaml")]
    [RibbonTab("ID_TransportTab", DisplayName = "物流路径规划")]
    [Command("OpenLogisticsPanel",
        DisplayName = "物流路径规划",
        ToolTip = "打开物流路径规划面板",
        LoadForCanExecute = true)]
    public class TransportRibbonHandler : CommandHandlerPlugin
    {
        private const string MainDockPanePluginKey = "NavisworksTransport.Main.Tian";
        private const string OpenLogisticsPanelCommandId = "OpenLogisticsPanel";
        private const string TransportRibbonTabId = "ID_TransportTab";

        public override int ExecuteCommand(string commandId, params string[] parameters)
        {
            try
            {
                if (!string.Equals(commandId, OpenLogisticsPanelCommandId, StringComparison.OrdinalIgnoreCase))
                {
                    LogManager.Warning($"[Ribbon] 未知命令: {commandId}");
                    return 1;
                }

                var pluginRecord = Autodesk.Navisworks.Api.Application.Plugins.FindPlugin(MainDockPanePluginKey) as DockPanePluginRecord;
                if (pluginRecord == null)
                {
                    throw new InvalidOperationException($"未找到物流路径规划面板插件: {MainDockPanePluginKey}");
                }

                var dockPane = pluginRecord.LoadPlugin() as DockPanePlugin;
                if (dockPane == null)
                {
                    throw new InvalidOperationException("物流路径规划面板加载失败");
                }

                dockPane.Visible = true;
                dockPane.ActivatePane();
                LogManager.Info("[Ribbon] 已通过正式工具栏打开物流路径规划面板");
                return 0;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[Ribbon] 执行命令失败: {ex.Message}", ex);
                return 1;
            }
        }

        public override CommandState CanExecuteCommand(string commandId)
        {
            if (string.Equals(commandId, OpenLogisticsPanelCommandId, StringComparison.OrdinalIgnoreCase))
            {
                return new CommandState
                {
                    IsEnabled = true,
                    IsVisible = true
                };
            }

            return new CommandState
            {
                IsEnabled = false,
                IsVisible = false
            };
        }

        public override bool CanExecuteRibbonTab(string ribbonTabId)
        {
            return string.Equals(ribbonTabId, TransportRibbonTabId, StringComparison.OrdinalIgnoreCase);
        }
    }
}
