using Ems.CollectService.Common;
using NLog;
using System;
using System.Collections.Generic;
using System.Text;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace Ems.CollectService.TouchSocket
{
    public class MyFixedHeaderRequestInfo: IFixedHeaderRequestInfo
    {

        #region 参数定义
        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; }

        private Logger logger = LogManager.GetCurrentClassLogger();

        private MsgUtil msgUtil = MsgUtil.Instance;
        #endregion

        public bool OnParsingBody(byte[] body)
        {
            //logger.Info("》》》接收客户端原始消息数据区: " + msgUtil.bytesToHexStr(body, (int)body.Length) + "\r\n");

            if (body.Length == this.m_bodyLength)
            {
                this.body = body;
                return true;
            }
            return false;
        }

        public bool OnParsingHeader(byte[] header)
        {
            //logger.Info("》》》接收客户端原始消息头: " + msgUtil.bytesToHexStr(header, header.Length) + "\r\n");

            if (header.Length == 10)
            {
                using (ByteBlock byteBlock = new ByteBlock(header))
                {
                    string m_BarcodeGroupCount = "";
                    int i_BarcodeGroupCount = 0;
                    byteBlock.Pos = 0;
                    byteBlock.Read(out m_sync, 10);
                    Array.Copy(header, 8, m_length, 0, 2);
                    if (header[7] == 0X01 || header[7] == 0X24 || header[7] == 0x08)
                    {
                        this.m_bodyLength = 2;//先把crc校验和end都获取。
                        return true;
                    }
                    else
                    {
                        m_BarcodeGroupCount = Convert.ToString(msgUtil.bytesToHexStr(m_length, m_length.Length));
                        i_BarcodeGroupCount = Convert.ToInt32("0x" + m_BarcodeGroupCount, 16);
                        if (i_BarcodeGroupCount != 0)
                        {
                            this.m_bodyLength = i_BarcodeGroupCount + 2;//先把crc校验和end都获取。
                            return true;
                        }
                    }

                }
            }
            return false;

        }
    }
}