using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iSTP_Embedded
{
    public class EmbeddedHealthData
    {
        public List<float[]> HealthData { get; private set; }
        public List<double> EmbeddedTime { get; private set; }

        private int Index { get { return (EmbeddedTime.Count > 0) ? (EmbeddedTime.Count - 1) : 0; } }
        private bool FirstTimestamp;
        private object GlobalLocker;

        public EmbeddedHealthData()
        {
            HealthData = new List<float[]>();
            EmbeddedTime = new List<double>();
            FirstTimestamp = false;
            GlobalLocker = new object();
        }

        public void UpdateData(EmbeddedPacket packet)
        {
            lock (GlobalLocker)
            {
                if (!FirstTimestamp)
                {
                    EmbeddedTime.Add(packet.MsgTimeStamp);
                    float[] element = new float[packet.MsgLength / 4];
                    for (int i = 0; i < element.Length; i++)
                        element[i] = packet[i];
                    HealthData.Add(element);
                    FirstTimestamp = true;
                }
                else if (packet.MsgTimeStamp > EmbeddedTime[Index])
                {
                    EmbeddedTime.Add(packet.MsgTimeStamp);
                    float[] element = new float[packet.MsgLength / 4];
                    for (int i = 0; i < element.Length; i++)
                        element[i] = packet[i];
                    HealthData.Add(element);
                }
            }
        }

        public bool ReadHealthData(out List<float[]> data, out List<double> timestamps)
        {       
            bool _res = false;
            data = new List<float[]>();
            timestamps = new List<double>();

            lock (GlobalLocker)
            {  
                if (HealthData.Count > 0)
                {
                    _res = true;

                    data = HealthData;
                    timestamps = EmbeddedTime;

                    FirstTimestamp = false;
                }
            }

            return _res;
        }

        public void ClearData()
        {
            lock (GlobalLocker)
            {
                HealthData.Clear();
                EmbeddedTime.Clear();
            }
        }
    }
}
