using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;

namespace NDSD_TouchSocket
{
    public class SendAnalysis
    {
        /// <summary>
        /// DO启动操作数据头
        /// </summary>
        private string DOperateHead = "01 05 00 ";

        /// <summary>
        /// DO启动操作数据尾
        /// </summary>
        private string DOpenData = " FF 00 ";

        /// <summary>
        /// DO关闭操作数据尾
        /// </summary>
        private string DCloseData = " 00 00 ";

        /// <summary>
        /// DO计时启动操作数据头
        /// </summary>
        private string DTimeOperateHead = " 01 07 00 ";

        /// <summary>
        /// DO计时启动操作码
        /// </summary>
        private string DTimeOpenData = " FF 00 ";

        public byte[] DTimeOpenDataAnalysis(byte port, int delay)
        {
            byte[] bytes = IntToDoubleByte(delay);
            Array.Reverse(bytes);
            string CrcData = DTimeOperateHead + port.ToString("X2") + DTimeOpenData + bytes.ToHexStrFromByte();
            return CrcCombine(CrcData);
        }

        /// <summary>
        /// DO开启
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public byte[] DOpenDataAnalysis(byte port)
        {
            string CrcData = DOperateHead + port.ToString("X2") + DOpenData; //结合
            return CrcCombine(CrcData);
        }

        /// <summary>
        /// DO关闭
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public byte[] DCloseDataAnlysis(byte port)
        {
            string CrcData = DOperateHead + port.ToString("X2") + DCloseData; //结合
            return CrcCombine(CrcData);
        }

        /// <summary>
        /// 结合CRC16
        /// </summary>
        /// <param name="CrcData"></param>
        /// <returns></returns>
        public byte[] CrcCombine(string CrcData)
        {
            byte[] body = CrcData.ToBytesFromHexString(); //byte的校验体
            int crc = CRC16.CalculateCRC(body, body.Length); //int32CRC值
            return body.Concat(IntToDoubleByte(crc)).ToArray();
        }

        /// <summary>
        /// int转换为两位Byte数字
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public byte[] IntToDoubleByte(int i)
        {
            byte highByte = (byte)(i >> 8); // 获取高字节
            byte lowByte = (byte)(i & 0xFF); // 获取低字节
            byte[] bytes = { lowByte, highByte };
            return bytes;
        }

    }

    
}
