using Microsoft.Extensions.Logging;
using Serilog.Core;
using SlnMesnac.Config;
using SlnMesnac.Model.AirportApiEntity;
using SlnMesnac.TouchSocket.Entity;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using TouchSocket.Sockets;

namespace SlnMesnac.TouchSocket
{

    public class BufferDataAnalysis
    {
        public static TcpVisionEntity BufferRootAnalysis(byte[] bytes)
        {
            TcpVisionEntity entity;
            //数据校验，从起始符开始到数据位，按字节求和得出的结果对256求余
            if(bytes.Length <= 2)
            {
                return null;
            }
            int checkDatalength = bytes.Length - 2;
            byte checksum = bytes[checkDatalength];
            byte[] checkData = new byte[checkDatalength];
            Array.Copy(bytes, 0, checkData, 0, checkDatalength);
            int sum = 0;
            foreach (byte b in checkData)
            {
                sum += b;
            }
            int count = sum % 256;
            if (count == checksum)
            {
                entity = new TcpVisionEntity();
                entity.Checksum = checksum;
            }
            else
            {
                return null;
            }
            int index = 2;

            //取序列号
            entity.SN = new byte[2] { bytes[index], bytes[index + 1] };
            index += 2;

            //取时间戳
            entity.Timestamp = new byte[4] { bytes[index], bytes[index + 1], bytes[index + 2], bytes[index + 3] };
            index += 4;

            //取命令字
            entity.Command = bytes[index];
            index += 1;

            //取数据位长度
            entity.DataLength = bytes[index];
            index += 1;

            //取数据位
            byte[] dataBytes = new byte[entity.DataLength];
            Array.Copy(bytes, index, dataBytes, 0, entity.DataLength);
            entity.DataBytes = dataBytes;
            index += entity.DataLength;
            return entity;
        }

        public byte[] DataCombine(byte[] bytes)
        {

            return null;
        }

        public static byte[] GetCurrentUnixTimestampAsBytes()
        {
            // 获取当前的Unix时间戳，表示自1970-01-01以来的秒数
            int unixTimestamp = (int)(DateTimeOffset.UtcNow.ToUnixTimeSeconds());
            // 将时间戳转换为字节数组
            byte[] bytes = BitConverter.GetBytes(unixTimestamp);
            return bytes;
        }

    }
}
