using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using UIShare.ViewModelBase;
using ZLGUSBCANFD;

namespace CANModule.ViewModels
{
    public class SelectCanMessageViewModel : DialogViewModelBase
    {
        #region 字段
        private ZLGCANFD? _canfd;
        #endregion

        #region 属性
        public DialogCloseListener RequestClose { get; set; }

        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 = "CollectCANSignalSetting";
        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 (!string.IsNullOrEmpty(value) && _canfd != null)
                    {
                        var db = _canfd.DBCParser.MsgDatabase;
                        if (MessageChannel >= 0 && MessageChannel < db.Count)
                        {
                            var targetMsg = db[MessageChannel]
                                .FirstOrDefault(x => $"[0x{x.msg_id:X}]{x.msg_name}" == value);

                            if (targetMsg != null && targetMsg.signal_Name != null)
                            {
                                SignalList = new ObservableCollection<string>(targetMsg.signal_Name);
                            }
                            else
                            {
                                SignalList = new ObservableCollection<string>();
                            }
                        }
                    }
                    else
                    {
                        SignalList = new ObservableCollection<string>();
                    }
                }
            }
        }

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

        private int _MessageChannel = -1;
        public int MessageChannel
        {
            get => _MessageChannel;
            set
            {
                if (_MessageChannel != value)
                {
                    _MessageChannel = value;

                    // 1. 先安全清空旧的选择项和信号列表
                    SelectedMessage = null;
                    SelectedSignal = null;
                    SignalList = new ObservableCollection<string>();

                    // 2. 刷新当前通道的报文列表
                    if (_canfd != null)
                    {
                        var db = _canfd.DBCParser.MsgDatabase;
                        if (db != null && value >= 0 && value < db.Count)
                        {
                            MessageList = new ObservableCollection<string>(
                                db[value].Select(s => $"[0x{s.msg_id:X}]{s.msg_name}")
                            );
                        }
                        else
                        {
                            MessageList = new ObservableCollection<string>();
                        }
                    }
                    else
                    {
                        MessageList = new ObservableCollection<string>();
                    }

                    RaisePropertyChanged();
                }
            }
        }
        #endregion

        #region 命令
        public ICommand CloseCommand { get; set; }
        public ICommand GetSelectedMessageCommand { get; set; }
        public ICommand GetSelectedSignalCommand { get; set; }
        public ICommand LoadCommand { get; set; }
        #endregion

        public SelectCanMessageViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            CloseCommand = new DelegateCommand(Close);
            GetSelectedMessageCommand = new DelegateCommand(GetSelectedMessage);
            GetSelectedSignalCommand = new DelegateCommand(GetSelectedSignal);
            LoadCommand = new DelegateCommand(Load);
        }

        #region Dialog 生命周期
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            _canfd = parameters.GetValue<ZLGCANFD>("CANFD");
        }
        #endregion

        #region 命令处理
        private void Close()
        {
            RequestClose.Invoke();
        }

        private void Load()
        {
            int maxCh = _canfd?.DBCParser.MaxChannels ?? 4;
            ChannelList = new ObservableCollection<int>(Enumerable.Range(0, maxCh));
        }

        private void GetSelectedSignal()
        {
            if (!string.IsNullOrEmpty(SelectedSignal))
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Clipboard.SetDataObject(SelectedSignal);
                });
            }
        }

        private void GetSelectedMessage()
        {
            if (!string.IsNullOrEmpty(SelectedMessage) && SelectedMessage.Contains(']'))
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Clipboard.SetDataObject(SelectedMessage);
                });
            }
        }
        #endregion
    }
}
