using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Aitex.Core.UI.MVVM;
using MECF.Framework.Simulator.Core.Commons;
using MECF.Framework.Simulator.Core.Driver;
using Venus_Simulator.Devices;
using Venus_Simulator.Instances;

namespace Venus_Simulator.Views
{
    /// <summary>
    /// Simu_CometRFView.xaml 的交互逻辑
    /// </summary>
    public partial class Simu_CometRFView : UserControl
    {
        public Simu_CometRFView()
        {
            InitializeComponent();
            this.DataContext = new CometRFSimulatorViewModel("CometRFViewModel");
            this.Loaded += OnViewLoaded;
        }

        private void OnViewLoaded(object sender, RoutedEventArgs e)
        {
            (DataContext as TimerViewModelBase)?.Start();
        }
    }

    class CometRFSimulatorViewModel : TimerViewModelBase
    {
        int port = 502;
        public ICommand ClearLogCommand { get; set; }
        public ICommand EnableCommand { get; set; }
        public ICommand DisableCommand { get; set; }
        public string Title
        {
            get { return "CometRF Simulator"; }
        }
        public ObservableCollection<TransactionLogItem> TransactionLogItems { get; set; }
        private CometRFSocketServer _cometRFServer;

        public CometRFSimulatorViewModel(string name) : base(name)
        {
            _cometRFServer = new CometRFSocketServer(port);
            ClearLogCommand = new DelegateCommand<string>(ClearLog);
            EnableCommand = new DelegateCommand<string>(Enable);
            DisableCommand = new DelegateCommand<string>(Disable);
            TransactionLogItems = new ObservableCollection<TransactionLogItem>();
            _cometRFServer.MessageOut += _simulator_MessageOut;
            _cometRFServer.MessageIn += _simulator_MessageIn;
        }

        private void Disable(string obj)
        {
            
        }

        private void Enable(string obj)
        {
            
        }

        private void ClearLog(string obj)
        {
            TransactionLogItems.Clear();
        }

        private void _simulator_MessageIn(string obj)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                TransactionLogItems.Add(new TransactionLogItem() { Incoming = obj, OccurTime = DateTime.Now.ToString("HH:mm:ss.fff") });

            }));
        }

        private void _simulator_MessageOut(string obj)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                TransactionLogItems.Add(new TransactionLogItem() { Outgoing = obj, OccurTime = DateTime.Now.ToString("HH:mm:ss.fff") });

            }));
        }

        protected override void Poll()
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {


                InvokeAllPropertyChanged();

            }));
        }
    }
}