using BPA.Message;
using BPASmartClient.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPASmartClient.Business
{
    /// <summary>
    /// 状态管理器
    /// </summary>
    public class StatusMgr : IPlugin
    {
        //运行标识
        private bool running = false;
        //设备管理
        private DeviceMgr deviceMgr;
        private MQTTMgr mqttMgr;
        DeviceStatus deviceStatus = new DeviceStatus();
        private bool wholeDeviceHealth;


        private Dictionary<int, Dictionary<string, object>> wholeDeviceStatus = new Dictionary<int, Dictionary<string, object>>();

        public void Initialize()
        {
            deviceMgr = Plugin.GetInstance().GetPlugin<DeviceMgr>();
            mqttMgr = Plugin.GetInstance().GetPlugin<MQTTMgr>();
        }

        public void Start()
        {
            running = true;
            ThreadManage.GetInstance().Start(() =>
            {
                while (running)
                {
                    wholeDeviceHealth = true;
                    foreach (var device in deviceMgr.GetDevices())
                    {
                        wholeDeviceStatus[device.DeviceId] = device.Status.GetStatus();
                    }
                    Thread.Sleep(50);
                }
            }, "设备状态收集", true);

            deviceStatus.BatchingInfo = new List<BPA.Models.BatchingInfo>();

            ThreadManage.GetInstance().Start(() =>
            {
                while (running)
                {
                    wholeDeviceHealth = true;
                    foreach (var device in deviceMgr.GetDevices())
                    {
                        wholeDeviceStatus[device.DeviceId] = device.Status.GetStatus();
                        deviceStatus.Healthy = device.IsHealth ? BPA.Message.Enum.DeviceHealthy.Health : BPA.Message.Enum.DeviceHealthy.UnHealth;
                        deviceStatus.DeviceType = device.DeviceType;
                        var msg = BPAPackage.Make(deviceStatus, device.DeviceId, device.DeviceType);
                        mqttMgr.Publish(TopicDefine.GetInstance().PushHeartbeatTopics[device.DeviceType], msg.Serialize());
                    }
                    Thread.Sleep(1000);
                }
            }, "设备心跳上报", true);
        }

        public void Dispose()
        {
            running = false;
        }


    }
}
