using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using DPackLib;
using McLaren_WPF.Events;
using Microsoft.Practices.Unity;
using Prism.Events;

namespace McLaren_WPF.Controls
{

    public partial class PilotPanel 
    {
        [Dependency] public IEventAggregator EventAggregator { get; set; }
        public string Description { get; set; }
        private string dataPath { get; set; }
        private DispatcherTimer resTimer;
        List<string> messageList = new List<string>();
        BinSerializer serializer { get; set; }
        private string lastMessage { get; set; }


        public PilotPanel()
        {
            InitializeComponent();
        }

        public void StartReception()
        {
            DescriptionTxt.Text = Description;
            dataPath = Path.Combine(CommonConstants.RootDir, Description + ".dat");
            serializer = new BinSerializer();
            CreateTimer();
        }

        private void CreateTimer()
        {
            resTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
            resTimer.Tick += GenTimer_Tick;
            resTimer.Start();
        }

        private void GenTimer_Tick(object sender, EventArgs e)
        {
            ReadData();
        }

        private void ReadData()
        {
            DataPackEventArgs dataPack = serializer.DeSerializeData(dataPath);
            if (dataPack == null || lastMessage == dataPack.Message) return;

            lastMessage = dataPack.Message;

            messageList.Add(dataPack.Message);

            if (messageList.Count > 20)
            {
                messageList = Enumerable.Reverse(messageList).Take(20).Reverse().ToList();
            }
           
            PilotText.Text = string.Join("\r\n", messageList.ToArray());
            PilotText.ScrollToEnd();

            DelayTxt.Text = "Delay: "
                + new TimeSpan(DateTime.Now.Ticks - dataPack.DateTimeTicks).TotalMilliseconds.ToString("0") + " ms";
        }

        private void BtnSendMessage_Click(object sender, RoutedEventArgs e)
        {
            var arg = new DataPackEventArgs
            {
                IsReturned = true,
                ReplyMessage = MessageText.Text
            };
            EventAggregator?.GetEvent<DataPackEvent>().Publish(arg);
        }

    }
}
