using System;
using System.Linq;
using System.Text;
using TouchSocket.Sockets;

namespace Rdh.SocketServer.Client.Models
{
    /// <summary>
    /// 固定包头和包尾的适配器  参考文档 https://www.yuque.com/rrqm/touchsocket/55e5bbf58745fa639dba511c7bcd54d1
    /// </summary>
    public class ElectronicMedicineKitBetweenAndDataHandlingAdapter : CustomBetweenAndDataHandlingAdapter<ElectronicMedicineKitBetweenAndRequestInfo>
    {
        public ElectronicMedicineKitBetweenAndDataHandlingAdapter() { MinSize = 5; }
        public override byte[] StartCode => ElectronicMedicineKitBetweenAndRequestInfo.Header;
        public override byte[] EndCode => ElectronicMedicineKitBetweenAndRequestInfo.Footer;

        protected override ElectronicMedicineKitBetweenAndRequestInfo GetInstance()
        {
            return new ElectronicMedicineKitBetweenAndRequestInfo();
        }
    }

    public class ElectronicMedicineKitBetweenAndRequestInfo : IBetweenAndRequestInfo
    {
        private const string _header = "***";
        private const string _footer = "@@@";
        private static Encoding _electronicMedicineKitEncoding = Encoding.GetEncoding("gb2312");

        public static byte[] Header { get { return _electronicMedicineKitEncoding.GetBytes(_header); } }
        public static byte[] Footer { get { return _electronicMedicineKitEncoding.GetBytes(_footer); } }
        public static Encoding ElectronicMedicineKitEncoding { get { return _electronicMedicineKitEncoding; } }
        public string BoxId { get; private set; }
        public ElectronicMedicineKitFunctionTypes FunctionType { get; private set; }
        public string Data { get; private set; }


        public void OnParsingBody(byte[] body)
        {
            BoxId = _electronicMedicineKitEncoding.GetString(body.Take(3).ToArray());
            FunctionType = (ElectronicMedicineKitFunctionTypes)Convert.ToByte(_electronicMedicineKitEncoding.GetString(body.Skip(3).Take(2).ToArray()), 16);
            if (body.Length > 5)
            {
                Data = _electronicMedicineKitEncoding.GetString(body.Skip(5).ToArray());
                Data = Data.Trim('#');
            }
        }

        public bool OnParsingEndCode(byte[] endCode)
        {
            return endCode.SequenceEqual(Footer);
        }

        public bool OnParsingStartCode(byte[] startCode)
        {
            return startCode.SequenceEqual(Header);
        }
    }
}
