using Common.PubEvent;
using OxyPlot;
using ProcessManager.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml.Linq;

namespace ProcessManager.ViewModels
{
    public class DevicesViewModel:BindableBase,INavigationAware
    {
        public ICommand WindowLoadedCommand { get; set; }
        public IEventAggregator _eventAggregator { get; set; }
        public string Title { get; set; }
        private UserControl? _currentView;
        private System.Windows.Forms.Panel? _host;

        public DevicesViewModel(IContainerProvider containerProvider)
        {
            _eventAggregator = containerProvider.Resolve<IEventAggregator>();
            _eventAggregator.GetEvent<StartProcessEvent>().Subscribe(GetProcess);
            WindowLoadedCommand =new DelegateCommand(OnWindowLoaded);
        }

        private void GetProcess((string exeName, bool isStart) msg)
        {
            if(Title!= msg.exeName) return;
            if (_currentView == null) return;
            if (!msg.isStart) return;
            WindowEmbedHelper.FindAndEmbedWindow(msg.exeName, _host);
        }

        private void OnWindowLoaded()
        {
            
        }
        #region 导航
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
           
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            Title= navigationContext.Parameters.GetValue<string>("Title");
            string viewName = navigationContext.Parameters.GetValue<string>("viewName");
            _currentView = navigationContext.NavigationService.Region .ActiveViews .FirstOrDefault() as UserControl;
            if (_currentView != null)
            {
                // 反射拿 Host 属性
                var hostProp = _currentView.GetType().GetProperty("Host");
                _host = hostProp?.GetValue(_currentView) as System.Windows.Forms.Panel;
            }
            _eventAggregator.GetEvent<ChangeCurrentTagEvent>()
                .Publish(!string.IsNullOrEmpty(viewName) ? viewName : Title);

        }

        #endregion
    }
}
