using BPA.Utility;
using HBLConsole.Communication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HBLDevice.Coffee
{
    /// <summary>
    /// 指令封装
    /// </summary>
    internal class CommandHandler
    {
        byte[] cmdAsk;
        private SerialPortClient commProxy;
        private DrCoffeePackage drinksOrder=new DrCoffeePackage();

        public Action<bool> PauseAsk { get; set; }
        /// <summary>
        /// 初始化
        /// </summary>
        internal void Init(SerialPortClient commProxy)
        {
            this.commProxy = commProxy;

            DrCoffeePackage package = new DrCoffeePackage();
            package.CommCmd = DrCoffeeCommCmd.饮品制作指令;
            cmdAsk = DrCoffee.Packe(package);
            drinksOrder.CommCmd = DrCoffeeCommCmd.饮品制作指令;

            EventBus.GetInstance().Subscribe<MakeCoffeeEvent>(MakeCoffeeEventHandle);
            EventBus.GetInstance().Subscribe<CancelMakeCoffeeEvent>(CancelMakeCoffeeEventHandle);
            EventBus.GetInstance().Subscribe<CoffeeCommCmdEvent>(CoffeeCommCmdEventHandle);

        }

        private void CoffeeCommCmdEventHandle(IEvent @event, EventBus.EventCallBackHandle callBack)
        {
            PauseAsk?.Invoke(true);
            Thread.Sleep(200);
            drinksOrder.CommCmd = ((CoffeeCommCmdEvent)@event).CommCmd;
            commProxy.SendData(DrCoffee.Packe(drinksOrder));
            Thread.Sleep(200);
            PauseAsk?.Invoke(false);
        }

        private void CancelMakeCoffeeEventHandle(IEvent @event, EventBus.EventCallBackHandle callBack)
        {
            PauseAsk?.Invoke(true);
            Thread.Sleep(200);
            drinksOrder.CommCmd = DrCoffeeCommCmd.取消应用指令;
            drinksOrder.DrinksCode = 0;
            commProxy.SendData(DrCoffee.Packe(drinksOrder));
            Thread.Sleep(200);
            PauseAsk?.Invoke(false);
        }

        private void MakeCoffeeEventHandle(IEvent @event, EventBus.EventCallBackHandle callBack)
        {
            PauseAsk?.Invoke(true);
            Thread.Sleep(200);
            drinksOrder.CommCmd = DrCoffeeCommCmd.饮品制作指令;
            drinksOrder.DrinksCode = ((MakeCoffeeEvent)@event).DrinkCode;
            commProxy.SendData(DrCoffee.Packe(drinksOrder));
            
            Thread.Sleep(200);
            PauseAsk?.Invoke(false);
        }

        /// <summary>
        /// 发送状态询问
        /// </summary>
        internal byte[] GetStatusAsk()
        {
            return cmdAsk;
        }
    }
}
