using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HBLConsole.Model;
using HBLConsole.Service;
using HBLConsole.GVL;
using HBLConsole.Communication;
using BPA.Message;
using HBLConsole.Business;
using HBLConsole.Factory;

namespace HBLConsole.MainConsole
{
    public class Main
    {

        private volatile static Main _Instance;
        public static Main GetInstance => _Instance ?? (_Instance = new Main());
        private Main() { }

        List<string> Topics = new List<string>();

        public void DataInit()
        {
            Json<MorkOrderPushPar>.GetInstance.Read();
            Json<BatchingInfoPar>.GetInstance.Read();
        }

        public void DataSave()
        {
            Json<MorkOrderPushPar>.GetInstance.Save();
            Json<BatchingInfoPar>.GetInstance.Save();
            TextHelper.GetInstance.SaveLogInfo(MessageLog.GetInstance.LogInfo, "LogInfo");
        }

        public void BusinessInit()
        {
            ThreadManagerment.GetInstance.Start(new Action(() =>
            {
                InternetInfo.GetInstance.ConfigInit();//从 consul 获取配置数据

                Topics.Clear();
                Topics.Add(TOPIC.GetInstance.GetOrderPushTopic(GeneralConfig.GetInstance.DeviceType, InternetInfo.GetInstance.ClientId));
                Topics.Add(TOPIC.GetInstance.GetBusinessTopic(GeneralConfig.GetInstance.DeviceType, InternetInfo.GetInstance.ClientId));

                SimpleFactory.GetInstance.DeviceInit();//设备初始化

                //MQTT 连接成功
                MqttHelper.GetInstance.ConnectOk = new Action(() =>
                {
                    MqttHelper.GetInstance.MqttSubscriptionAsync(Topics.ToArray());//主题订阅

                    HeartbeatReport.GetInstance.Init();//心跳上报

                    ServerData.GetInstance.Init();//数据处理初始化

                    //接收MQTT消息
                    MqttHelper.GetInstance.MqttReceive = new Action<MQTTnet.MqttApplicationMessageReceivedEventArgs>((receivce) =>
                    {
                        ServerData.GetInstance.ReceiveData(Encoding.UTF8.GetString(receivce.ApplicationMessage.Payload));
                    });
                });

                //MQTT 重连成功
                MqttHelper.GetInstance.Reconnection = new Action(() => { MqttHelper.GetInstance.MqttSubscriptionAsync(Topics.ToArray()); });

                //MQTT 连接
                MqttHelper.GetInstance.MqttInitAsync(InternetInfo.GetInstance.MqttUserName,
                    InternetInfo.GetInstance.MqttPassword,
                    InternetInfo.GetInstance.MqttAddress,
                    InternetInfo.GetInstance.MqttPort,
                    DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"));
            }), "业务逻辑初始化");
        }

    }
}
