using System;
using System.IO;
using System.Windows.Threading;
using DPackLib;

namespace McLaren_WPF.Controls
{
    public partial class SpeedPanel 
    {
        public string Description { get; set; }

        #region Private Var

        private BinSerializer serializer { get; set; }
        private string dataPath { get; set; }
        private DispatcherTimer resTimer;
        private double tempSpeed =0;
        private bool maxSpeedReached = false;

        #endregion

        public SpeedPanel()
        {
            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) return;
            InfoTxt.Text = dataPack.Message;

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

            if (maxSpeedReached)
            {
                tempSpeed -= dataPack.Data*20;
                if (tempSpeed <= 0)
                {
                    tempSpeed = 0;
                    maxSpeedReached = false;
                }
            }
            else
            {
                tempSpeed += dataPack.Data * 20;
                if (tempSpeed > 300) {maxSpeedReached = true;}
            }

            SpeedNeedle.Value = tempSpeed;
            SpeedTxt.Text = tempSpeed.ToString("0")+ " km/h";
        }
    }
}
