using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Model;
using TSMasterCAN;
using UIShare.GlobalVariable;
using UIShare.PubEvent;
using UIShare.UIViewModel;

namespace CANModule.ViewModels
{
    public class CollectCANSignalSettingViewModel : BindableBase, IDialogAware
    {
        #region 属性
        public ObservableCollection<CANSignalConfig> ConfigurationList
        {
            get => _systemConfig.ConfigurationList;
            set
            {
                if(_systemConfig.ConfigurationList != value)
                {
                    _systemConfig.ConfigurationList = value;
                    RaisePropertyChanged();
                }
            }
        }

        private ObservableCollection<int> _ChannelList;
        public ObservableCollection<int> ChannelList
        {
            get => _ChannelList;
            set => SetProperty(ref _ChannelList, value);
        }
        private ObservableCollection<string> _messageList;
        public ObservableCollection<string> MessageList
        {
            get => _messageList;
            set => SetProperty(ref _messageList, value);
        }

        private ObservableCollection<string> _signalList;
        public ObservableCollection<string> SignalList
        {
            get => _signalList;
            set => SetProperty(ref _signalList, value);
        }

        private string _title= "信号采集设置";
        public string Title
        {
            get => _title;
            set => SetProperty(ref _title, value);
        }
        private string _selectedMessage;
        public string SelectedMessage
        {
            get => _selectedMessage;
            set
            {
                if (SetProperty(ref _selectedMessage,value))
                {
                    if (value != null && value != "")
                    {
                        SignalList = new(DBCParse.MsgDatabase[MessageChannel].Where(x => $"[0x{x.msg_id:X}]{x.msg_name}" == value).First().signal_Name);
                    }
                }
            }
        }

        private CANSignalConfig _SelectedItem;
        public CANSignalConfig SelectedItem
        {
            get => _SelectedItem;
            set => SetProperty(ref _SelectedItem, value);
        }
        private string _selectedSignal;
        public string SelectedSignal
        {
            get => _selectedSignal;
            set => SetProperty(ref _selectedSignal, value);
        }

        private int _MessageChannel;
        public int MessageChannel
        {
            get => _MessageChannel;
            set
            {
                if (_MessageChannel != value)
                {
                    _MessageChannel = value;
                    MessageList = new(DBCParse.MsgDatabase[value].Select(s => $"[0x{s.msg_id:X}]{s.msg_name}"));
                    SignalList = new();
                    SelectedMessage = null;
                    SelectedSignal = null;
                    RaisePropertyChanged();
                }
            }
        }

        private int _collectionInterval=1000;
        public int CollectionInterval
        {
            get => _collectionInterval;
            set => SetProperty(ref _collectionInterval, value);
        }
        #endregion Properties
        public ICommand AddCommand { get; set; }
        public ICommand CloseCommand { get; set; }  
        public ICommand LoadCommand { get; set; }  
        public ICommand SaveCommand { get; set; }  
        public ICommand DeleteCommand { get; set; }  
        public DialogCloseListener RequestClose { get; set; }
        public IEventAggregator _eventAggregator { get; set; }
        private SystemConfig _systemConfig;
        public CollectCANSignalSettingViewModel(IContainerProvider containerProvider)
        {
            _eventAggregator=containerProvider.Resolve<IEventAggregator>();
            _systemConfig= containerProvider.Resolve<SystemConfig>();
            CloseCommand = new DelegateCommand(Close);
            AddCommand = new DelegateCommand(Add);
            LoadCommand = new DelegateCommand(Load);
            SaveCommand = new DelegateCommand(Save);
            DeleteCommand = new DelegateCommand(Delete);
        }

        private void Delete()
        {
            ConfigurationList.Remove(SelectedItem);
        }

        private void Save()
        {
            _eventAggregator.GetEvent<CollectedCANMessageChangedEvent>().Publish();
            ConfigService.Save(_systemConfig);
        }

        private void Load()
        {
            ChannelList = new ObservableCollection<int>(Enumerable.Range(0, 12));
        }


        private void Add()
        {
            if (string.IsNullOrEmpty(SelectedSignal) || string.IsNullOrEmpty(SelectedMessage)||CollectionInterval<100)
            {
                return;
            }
            string hexString = ExtractHex(SelectedMessage);
            if (string.IsNullOrEmpty(hexString))
            {
                return;
            }
            int decimalValue = ConvertHexToDecimal(hexString);
            if (ConfigurationList.Where(x => x.SignalName == SelectedSignal&&x.Channel==MessageChannel).FirstOrDefault() != null) return;
                ConfigurationList.Add(new CANSignalConfig
            {
                CollectionID = Guid.NewGuid(),
                Channel = MessageChannel, 
                MessageName = ExtractMessageName(SelectedMessage),
                SignalName = SelectedSignal,
                MessageID = decimalValue,
                CollectionInterval = CollectionInterval
            });
        }
        private string ExtractHex(string input)
        {
            int startIndex = input.IndexOf("0x") + 2;
            int endIndex = input.IndexOf("]", startIndex); 
            if (startIndex >= 2 && endIndex > startIndex)
            {
                return input.Substring(startIndex, endIndex - startIndex);
            }
            return string.Empty;
        }
        private int ConvertHexToDecimal(string hex)
        {
            try
            {
                return Convert.ToInt32(hex, 16);
            }
            catch (FormatException)
            {
                return -1; 
            }
        }
        private string ExtractMessageName(string input)
        {
            var parts = input.Split(']');
            return parts.Length > 1 ? parts[1] : string.Empty; 
        }

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

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            if (DBCParse.MsgDatabase.Count == 0 || DBCParse.MsgDatabase[0].Count==0)
            {

            }
            MessageList = new(DBCParse.MsgDatabase[0].Select(s => $"[0x{s.msg_id:X}]{s.msg_name}"));
        }
    }
}
