using MesWorkMqtt;
using MisDataFunction;
using MQTTnet;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Receiving;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MisDataSaveDate
{
    public partial class SaveData : Form
    {
        public SaveData()
        {
            InitializeComponent();
        }

        private void SaveData_Load(object sender, EventArgs e)
        {
            //Task.Run(() => StartAsync());

            Mqtt.StartAsync();
            Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);
            Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);
            Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived);

            string url;
            string topic;
            url = ConfigurationManager.AppSettings["MqttUrl"];
            topic = ConfigurationManager.AppSettings["MqttTargetTopicTagTypeCodeID"];
            new InitMqtt2(url, topic);


            MesServerWork.MIS_BASE.InitHashtable_MesServerCode();


        }
        private void OnSubscriberConnected(MqttClientConnectedEventArgs x)
        {
            var rec = x.AuthenticateResult.ResultCode.ToString();
            //label_State.Text = rec;
        }

        private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x)
        {
            //var rec = x.AuthenticateResult.ResultCode.ToString();
            //label_State.Text = rec;
        }

        private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x)
        {
            var rec = x.ApplicationMessage.ConvertPayloadToString();
            ThreadPool.QueueUserWorkItem(MisDataSaveDate.Funtion.MIS_Funtion, rec);
        }



    }
}
