using HighWayIot.Repository.domain;
using HighWayIot.Repository.service.Impl;
using HighWayIot.TouchSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace RFIDSocket
{
    public class DataAnalysis
    {
        private static readonly Lazy<DataAnalysis> lazy = new Lazy<DataAnalysis>(() => new DataAnalysis());

        public static DataAnalysis Instance => lazy.Value;

        public List<RFIDContent> rFIDContents = new List<RFIDContent>();
        public List<RFIDHeartbeat> rFIDHeartbeats = new List<RFIDHeartbeat>();
        public List<RFIDHeartbeat> HeartbeatsState = new List<RFIDHeartbeat>();
        public List<RFIDState> rFIDStates = new List<RFIDState>();
        public List<RFIDState> AlarmState = new List<RFIDState>();

        public void GetData()
        {
            BaseContentServiceImpl baseContentServiceImpl = new BaseContentServiceImpl();
            BaseHeartbeatServiceImpl baseHeartbeatServiceImpl = new BaseHeartbeatServiceImpl();
            BaseStateServiceImpl baseStateServiceImpl = new BaseStateServiceImpl();

            rFIDContents = baseContentServiceImpl.GetContentInfos().Reverse<RFIDContent>().Take(200).ToList();

            rFIDStates = baseStateServiceImpl.GetStateInfos();

            var StateGroup = rFIDStates.GroupBy(x => x.DeviceNo);

            AlarmState.Clear();

            foreach(var a in StateGroup)
            {
                var b = a.LastOrDefault();
                if (b.DeviceState)
                {
                    AlarmState.Add(b);
                }
            }

            rFIDHeartbeats = baseHeartbeatServiceImpl.GetHeartbeatInfos();

            var HeartBeatGroup = rFIDHeartbeats.GroupBy(x => x.DeviceNo);

            HeartbeatsState.Clear();

            foreach (var a in HeartBeatGroup)
            {
                var b = a.LastOrDefault();
                if (DateTime.Now - b.BeatTime > TimeSpan.FromSeconds(10))
                {
                    b.TimeSpan = SecondToTime(Convert.ToInt32((DateTime.Now - b.BeatTime).TotalSeconds));
                    HeartbeatsState.Add(b);
                }
            }
        }

        private string SecondToTime(int t)
        {
            int m = t / 60;
            int s = t % 60;
            if (m == 0)
            {
                return "00 分 " + s.ToString("00") + " 秒";
            }
            return m.ToString("00") + " 分 " + s.ToString("00") + " 秒";
        }
    }
}
