using Azure;
using BOB;
using Common.PubEvent;
using ProcessManager.Helpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ProcessManager.ViewModels
{
    public class MenuViewModel : BindableBase, INavigationAware
    {
        private ObservableCollection<SystemConfig> _configList;

        public ObservableCollection<SystemConfig> ConfigList
        {
            get => _configList;
            set => SetProperty(ref _configList, value);
        }

        private readonly IDialogService _dialogService;
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;
        private Dictionary<string, Process> ProcessDic { get; set; } = new Dictionary<string, Process>();
        public ICommand StartCommand { get; set; }
        public ICommand EditCommand { get; set; }
        public ICommand WindowLoadedCommand { get; set; }
     
        public MenuViewModel(IContainerProvider containerProvider)
        {
            _dialogService = containerProvider.Resolve<IDialogService>();
            _regionManager = containerProvider.Resolve<IRegionManager>();
            _eventAggregator = containerProvider.Resolve<IEventAggregator>();
            EditCommand = new DelegateCommand<string>(OnEdit);
            StartCommand = new DelegateCommand<string>(OnStart);
            WindowLoadedCommand = new DelegateCommand(OnWindowLoaded);
        }

     

        private void OnWindowLoaded()
        {
            if (ConfigList != null) ConfigList.Clear();
            var JSONFiles = Directory.GetFiles(JsonHelper.SystemPath, "*.json")
                         .Where(f => !f.EndsWith("UpdateInfo.json", StringComparison.OrdinalIgnoreCase))
                         .ToArray();
            foreach (var file in JSONFiles)
            {
                JsonHelper.ConfigFile = file;
                var config = JsonHelper.LoadFromFile();
                if (ConfigList == null)
                {
                    ConfigList = new ObservableCollection<SystemConfig>();
                }
                ConfigList.Add(config);
            }
        }

        private void OnStart(string deviceName)
        {
            if (ProcessDic.ContainsKey(deviceName))
            {
                MessageBox.Show("进程已启动");
                return;
            }
            try
            {
                string currentDir = Environment.CurrentDirectory;
                string exePath = Path.Combine(currentDir, "BOB.exe");
                if (!File.Exists(exePath))
                {
                    MessageBox.Show($"未找到文件: {exePath}");
                    return;
                }
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = exePath,
                    Arguments = deviceName,
                    UseShellExecute = true
                };
                var configToSave = ConfigList.FirstOrDefault(x => x.Title == deviceName);
                if (configToSave != null)
                {
                    JsonHelper.ConfigFile = Path.Combine(JsonHelper.SystemPath, $"{deviceName}.json");
                    JsonHelper.SaveToFile(configToSave);
                }
                var process = Process.Start(startInfo);
                process.EnableRaisingEvents = true;
                process.Exited += (s, args) =>
                {
                    ProcessDic.Remove(deviceName);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        OnWindowLoaded();
                    });
                };
                ProcessDic.Add(deviceName, process);
                string viewName = deviceName switch
                {
                    "设备1" => "DeviceOne",
                    "设备2" => "DeviceTwo",
                    "设备3" => "DeviceThree",
                    _ => "Other"
                };
                var parameters = new NavigationParameters
                {
                    { "Title", deviceName },
                    { "viewName", viewName },
                };
                _regionManager.RequestNavigate("MainRegion", viewName, parameters);
                _eventAggregator.GetEvent<StartProcessEvent>().Publish((deviceName, true));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动失败: {ex.Message}");
            }
        }

        private void OnEdit(string deviceName)
        {
            if (ProcessDic.ContainsKey(deviceName))
            {
                MessageBox.Show("请先关闭进程再进行编辑");
                return;
            }
            JsonHelper.ConfigFile = Path.Combine(JsonHelper.SystemPath, $"{deviceName}.json");
            var ConfigSystem = JsonHelper.LoadFromFile();
            var parameters = new DialogParameters
            {
                { "SystemConfig", ConfigSystem },
                { "Title", deviceName }
            };

            _dialogService.ShowDialog("Setting", parameters, r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    // 用户点击 OK
                }
            });
        }
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            _eventAggregator.GetEvent<ChangeCurrentTagEvent>().Publish("Menu");
        }
    }
}
