using HighWayIot.Log4net;
using HighWayIot.Rfid.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HighWayIot.Rfid
{
    /// <summary>
    /// RFID基础数据分析
    /// </summary>
    public class BaseRFIDDataAnalyse
    {
        private static LogHelper _logHelper = LogHelper.Instance;

        /// <summary>
        /// 基础接收数据解析
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static BaseReciveDataEntity BaseReceiveAnalyse(byte[] data)
        {
            BaseReciveDataEntity result = new BaseReciveDataEntity();

            int index = 0;
            index += 2;

            //取Length
            result.DataLength = data[index];
            index++;

            //取Code
            result.Code = data[index];
            index++;

            //取Status
            result.Status = data[index];
            index++;

            result.Data = new byte[result.DataLength];

            //取Data
            Array.Copy(data, 5, result.Data, 0, result.DataLength);
            index += result.DataLength;

            //算Xor
            result.Xor = data[index];
            int xor = 0;
            for (int i = 0; i < 3 + result.DataLength; i++)
            {
                xor ^= data[i + 2];
            }
            if(xor != data[data.Length - 2])
            {
                //_logHelper.Error("数据校验和未通过");
                return null;
            }

            return result;
        }

        /// <summary>
        /// 发送数据封装
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static byte[] BaseSendDataAnalyse(BaseSendDataEntity entity)
        {
            byte[] result = new byte[entity.Data.Length + 6];

            int index = 2;
            
            //指令头
            result[0] = 0xAA;
            result[1] = 0x55;
            
            //数据长度
            result[index] = (byte)entity.Data.Length;
            index++;

            //指令编号
            result[index] = entity.Code;
            index++;

            //数据
            Array.Copy(entity.Data, 0, result, 4, entity.Data.Length);
            index += entity.Data.Length;

            //校验和
            int xor = 0;
            for (int i = 0; i < 2 + entity.Data.Length; i++)
            {
                xor ^= result[i + 2];
            }
            result[index] = (byte)xor;
            index++;

            //帧尾
            result[index] = 0x0D;

            return result;
        }
    }
}
