using ProjectBase.Data.Logs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SIASUN.Autopilot.Device.Common
{
    /// <summary>
    /// 订阅类命令
    /// </summary>
    public class SubscribeCommand<T>
    {
        public string OperationId { get; set; }
        public event ReceiveMessageEventHandler ReceiveMessage;

        public SubscribeCommand(string msgOperationId)
        {
            this.OperationId = msgOperationId;
        }

        public void Subscribe()
        {
            EventManage.Instance.SubscribeEvent(OperationId, new EventProcessingHandler(ProcessPackage));
        }

        public void UnSubscribe()
        {
            EventManage.Instance.UnSubscribeEvent(OperationId, ProcessPackage);
        }

        private void ProcessPackage(PackageProcessingEventArgs e)
        {
            //接收到数据后触发ReceiveMessage处理。
            try
            {
                //通知
                if (ReceiveMessage != null)
                {
                    var args = new ReceiveMessageEventArgs((T)e.PackageBytes[0]);
                    ReceiveMessage(args);
                }
            }
            catch (Exception ex)
            {
                LogHelper.log.Error(string.Format("ProcessPackage事件出现未知异常{0}。", ex.ToString()));
                //TODO，日志
                var args = new ReceiveMessageEventArgs(null);
                ReceiveMessage(args);
            }
        }
    }
}
