using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace HBLDevice.Coffee
{
    public class DrCoffee
    {
        public const int LENGTH = 26;
        public const byte HEADER = 0x7E;
        public const byte END = 0x7E;

        public static DrCoffeePackage UnPack(byte[] datagram)
        {
            if (LENGTH != datagram.Length)
                return default(DrCoffeePackage);
            // 分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(LENGTH);
            // 将byte数组拷到分配好的内存空间
            Marshal.Copy(datagram, 0, structPtr, LENGTH);
            // 将内存空间转换为目标结构体
            DrCoffeePackage obj = (DrCoffeePackage)Marshal.PtrToStructure(structPtr, typeof(DrCoffeePackage));
            // 释放内存空间
            Marshal.FreeHGlobal(structPtr);
            // 返回结构体
            return obj;

        }

        public static byte[] Packe(DrCoffeePackage package)
        {
            package.Header = HEADER;
            package.Length = LENGTH;
            package.End = END;
            package.CalcCode = PackageCalcValideCode(package);
            // 创建byte数组
            byte[] bytes = new byte[LENGTH];
            // 分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(LENGTH);
            // 将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(package, structPtr, false);
            //从 内存空间拷到byte数组
            Marshal.Copy(structPtr, bytes, 0, LENGTH);
            // 释放内存空间
            Marshal.FreeHGlobal(structPtr);
            // 返回byte数组
            return bytes;
        }

        public static byte PackageCalcValideCode(DrCoffeePackage package)
        {
            var sum = (long)package.Length
                + (long)package.Warning
                + (long)package.Fault
                + (long)package.Status
                + (long)package.CommCmd
                + (long)package.ApplicationStatus
                + (long)package.DrinksCode
                + (long)package.ApplicationCode
                + (long)package.Retain;
            return (byte)(sum & 0xff);
        }
    }
}
