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

namespace McLaren_WPF.Controls
{
    public partial class TemperaturePanel 
    {
        public string Description { get; set; }
        private string dataPath { get; set; }
        private DispatcherTimer resTimer;
        BinSerializer serializer { get; set; }
        private double tempTmp = 0;
        private bool maxTmpReached = false;

        public TemperaturePanel()
        {
            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 (maxTmpReached)
            {
                tempTmp -= dataPack.Data * 5;
                if (tempTmp <= 0)
                {
                    tempTmp = 0;
                    maxTmpReached = false;
                }
            }
            else
            {
                tempTmp += dataPack.Data * 5;
                if (tempTmp > 120) { maxTmpReached = true; }
            }


            TemperatureBar.Value = tempTmp;
            TemperatureTxt.Text = tempTmp.ToString("0") + " °C";
        }
    }
}
