using HBLConsole.Communication;
using HBLConsole.Model;
using HBLConsole.Service;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;

namespace HBLDevice.ICChip
{
    public class ICChipMachine
    {
        //指令组装
        private CommandHandler commandHandler = new CommandHandler();
        //通讯代理
        SerialPortClient commProxy = null;
        //数据仓库
        private DataStorage<byte> dataStorage = new DataStorage<byte>();
        //主线程运行标识
        private bool running = false;
        //是否下发指令，主线程等待
        public Action<string> SendCallback;
        public Action<string> ReciveCallback;



        public ICChipMachine(string portName, BaudRates baud)
        {
            commProxy = new SerialPortClient(portName, baud);
            commProxy.SetDataStorage(dataStorage);
            commandHandler.Init(commProxy);
        }

        public void Start()
        {
            commProxy.Start();
            running = true;
            MainLoop();
        }

        public void Stop()
        {
        }

        private void MainLoop()
        {
            ThreadManage.GetInstance.StartLong(new Action(() =>
            {
                ResolveMsg();
                //Thread.Sleep(2000);
            }), "单片机解析线程");
        }

        private void ResolveMsg()
        {
            List<byte> temp = new List<byte>();
            //一系列解包
            while (dataStorage.GetSize() > 0)
            {
                byte item = dataStorage.GetData();
                if (item == 0xAA)
                {
                    temp.Add(item);
                    while (dataStorage.GetSize() < 4) { Thread.Sleep(5); }
                    while (temp.Count < 5)
                    {
                        temp.Add(dataStorage.GetData());
                    }
                    if (temp[4] == 0xBB)
                    {
                        var package = ByteToStructure(temp.ToArray());
                        ChipStatus.GetInstance().ProcessMsg(package);
                    }
                    temp.Clear();
                }
                continue;
            }
            Thread.Sleep(5);
        }

        /// <summary>  
        /// 由byte数组转换为结构体  
        /// </summary>  
        private ICChipPackage ByteToStructure(byte[] dataBuffer)
        {
            ICChipPackage structure = new ICChipPackage();
            int size = Marshal.SizeOf(typeof(ICChipPackage));
            IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
                structure = (ICChipPackage)Marshal.PtrToStructure(allocIntPtr, typeof(ICChipPackage));
            }
            finally
            {
                Marshal.FreeHGlobal(allocIntPtr);
            }
            return structure;
        }
    }

}
