using BOB;
using BOB.Models;
using Model;
using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;

namespace ProcessManager.ViewModels
{
    public class SettingViewModel : BindableBase, IDialogAware
    {
        private string _Title;

        public string Title
        {
            get => _Title;
            set => SetProperty(ref _Title, value);
        }
        private bool _SelectedDeviceType;
        //true为serialport ,false为tcp
        public bool SelectedDeviceType
        {
            get => _SelectedDeviceType;
            set => SetProperty(ref _SelectedDeviceType, value);
        }
        private DeviceConfigModel _SelectedDevice;

        public DeviceConfigModel SelectedDevice
        {
            get => _SelectedDevice;
            set
            {
                if(SetProperty(ref _SelectedDevice, value))
                {
                    if(value.CommunicationConfig is SerialPortConfig)
                    {
                        SelectedDeviceType = true;
                    }
                    else
                    {
                        SelectedDeviceType = false;
                    }
                }
            }
        }

        private SystemConfig _config;
        public SystemConfig Config
        {
            get => _config;
            set => SetProperty(ref _config, value);
        }

        public ObservableCollection<DeviceConfigModel> Devices { get; set; } = new ObservableCollection<DeviceConfigModel>();

        public DialogCloseListener RequestClose { get; set; }
        public ICommand SaveCommand { get; set; }
        public ICommand CancelCommand { get; set; }
        public SettingViewModel()
        {
            CancelCommand = new DelegateCommand(Cancel);
            SaveCommand = new DelegateCommand(Save);
        }

        private void Save()
        {
            try
            {
                //foreach(var d in Config.DeviceList)
                //{
                //    d.Id=Guid.NewGuid();
                //}
                JsonHelper.SaveToFile(Config);
                RequestClose.Invoke();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void Cancel()
        {
            RequestClose.Invoke();
        }

        public bool CanCloseDialog() => true;

        public void OnDialogClosed() { }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            // 从参数获取 SystemConfig
            if (parameters.ContainsKey("SystemConfig"))
            {
                Config = parameters.GetValue<SystemConfig>("SystemConfig");
                Devices.Clear();
                foreach (var d in Config.DeviceList)
                    Devices.Add(d);
            }
            if (parameters.ContainsKey("Title"))
            {
                Title= parameters.GetValue<string>("Title");
            }
        }
    }
}
