using BPA.MQTTClient;
using Microsoft.Extensions.Configuration;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Receiving;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPASmartClient.MQTT
{
    public class MQTTProxy
    {
        public Action<string> MessageRecive { get; set; }
        public Action Connected { get; set; }
        public Action LostConnect { get; set; }

        public bool IsConnected { get; set; }

        private IMqttClient client;

        public void Connect(string ip, int port, string clientId)
        {
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.AddMqttClientHostedService(p =>
            {
                p.Server = ip;
                p.Port = port;
                p.UserName = "rafiul";
                p.Password = "12345678";
                p.mqttClientConnectedHandlerDelegate = new MQTTnet.Client.Connecting.MqttClientConnectedHandlerDelegate(e =>
                {
                    IsConnected = true;
                    Connected?.Invoke();
                });
                //p.mqttClientDisconnectedHandlerDelegate = new MQTTnet.Client.Disconnecting.MqttClientDisconnectedHandlerDelegate(e =>
                //{
                //    IsConnected = false;
                //    LostConnect?.Invoke();
                //});
                p.ConnectedResult += (s, e) =>
                {
                    client = e;
                };
                p.MqttApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
                {
                    MessageRecive?.Invoke(Encoding.Default.GetString(e.ApplicationMessage.Payload));
                });
            });
        }

        public void CloseConnect()
        {
            client.Dispose();
        }

        public async void Publish(string topic, string content)
        {
            if (client.IsConnected)
                await client.PublishAsync(topic, content);
        }

        public async void Subscrib(params string[] topics)
        {
            foreach (var topic in topics)
            {
                await client.SubscribeAsync(new MqttTopicFilter() { Topic = topic, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
            }
        }
    }
}
