using System;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace HighWayAssemble.Protocol
{
    internal class MyFixedHeaderCustomDataHandlingAdapter : CustomFixedHeaderDataHandlingAdapter<MyRequestInfo>
    {
        public override int HeaderLength => 7;

        protected override MyRequestInfo GetInstance()
        {
            return new MyRequestInfo();
        }
    }
    public class MyRequestInfo : IFixedHeaderRequestInfo
    {
        private byte[] m_sync;
        private int m_bodyLength;
        private byte[] m_length = new byte[2];
        private byte[] body;
        public int BodyLength { get => m_bodyLength; }
        /// <summary>
        /// 报文头:5AA5
        /// </summary>
        public byte[] Header { get => m_sync; set => m_sync = value; }


        /// <summary>
        /// 自定义属性，标识实际数据
        /// </summary>
        public byte[] Body { get => body; set => body = value; }

        public bool OnParsingBody(byte[] body)
        {
            if (body.Length == this.m_bodyLength)
            {
                this.body = body;
                return true;
            }
            return false;
        }
        /// <summary>
        /// 接收客户端消息头
        /// </summary>
        /// <param name="header"></param>
        /// <returns></returns>
        public bool OnParsingHeader(byte[] header)
        {
            try
            {
                if (header.Length == 7)
                {
                    using (ByteBlock byteBlock = new ByteBlock(header))
                    {
                        string m_BarcodeGroupCount = "";
                        int i_BarcodeGroupCount = 0;
                        byteBlock.Pos = 0;
                        byteBlock.Read(out m_sync, 7);
                        Array.Copy(header, 5, m_length, 0, 2);
                        i_BarcodeGroupCount = BitConverter.ToUInt16(header, 5);

                        this.m_bodyLength = i_BarcodeGroupCount + 3;//先把crc校验和end都获取。


                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
