using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using VIZ.Framework.Core;
using VIZ.Package.Domain;
using VIZ.Package.Plugin;

namespace VIZ.Package.Module
{
    /// <summary>
    /// 热键控制器
    /// </summary>
    public class HotkeyController
    {
        /// <summary>
        /// 热键控制器
        /// </summary>
        /// <param name="vm">视图模型</param>
        public HotkeyController(MainViewModel vm)
        {
            this.MainViewModel = vm;
        }

        /// <summary>
        /// 主视图模型
        /// </summary>
        public MainViewModel MainViewModel { get; set; }

        /// <summary>
        /// 开始执行热键
        /// </summary>
        /// <param name="key">热键</param>
        public void BeginExecute(string key)
        {
            if (ApplicationDomainEx.IsHotkeySetting)
                return;

            if (string.IsNullOrWhiteSpace(key))
                return;

            WPFHelper.BeginInvoke(() =>
            {
                // 插件视图
                FrameworkElement pluginView = this.GetPluginView();

                HotkeyMessage msg = new HotkeyMessage();
                msg.Key = key;
                msg.View = pluginView;

                ApplicationDomainEx.MessageManager.Send(msg);

                if (!ApplicationDomainEx.IS_DEBUG)
                    return;

                Debug.WriteLine($"Hotkey: {key} , View: {pluginView?.ToString()}");
            });
        }

        /// <summary>
        /// 获取插件视图
        /// </summary>
        /// <returns>插件视图</returns>
        private FrameworkElement GetPluginView()
        {
            MainView view = this.MainViewModel.GetView<MainView>();
            if (view == null)
                return null;

            FrameworkElement element = view.dockLayoutManager.ActiveDockItem as FrameworkElement;
            if (element == null)
                return null;

            PluginInfo info = element.DataContext as PluginInfo;
            if (info == null)
                return null;

            FrameworkElement pluginView = null;
            info.View?.TryGetTarget(out pluginView);

            return pluginView;
        }
    }
}
