package main

import (
	"sync"

	"lc/common/mqtt"
)

var _mqttMgrOnce sync.Once
var _mqttMgrSingle *MQTTMgr

func GetMQTTMgr() *MQTTMgr {
	_mqttMgrOnce.Do(func() {
		_mqttMgrSingle = _newMQTTMgr()
	})
	return _mqttMgrSingle
}

type MQTTMgr struct {
	Cloud *MqttClient
}

func _newMQTTMgr() *MQTTMgr {
	return &MQTTMgr{
		Cloud: NewMqttClient(MQTTConfig.Mqtt_Server,
			MQTTConfig.Mqtt_Id,
			MQTTConfig.Mqtt_User,
			MQTTConfig.Mqtt_Password,
			3000, &EmptyMqttOnline{}),
	}

}

func (o *MQTTMgr) Subscribe(topic string, qos mqtt.QOS, handler mqtt.MessageHandler) {
	o.Cloud.Handle(topic, handler)
	err := o.Cloud.Subscribe(topic, qos)
	if err != nil {
		return
	}
}

func (o *MQTTMgr) UnSubscribe(topic string) {
	err := o.Cloud.Unsubscribe(topic)
	if err != nil {
		return
	}
}

func (o *MQTTMgr) Publish(topic string, payload string, qos mqtt.QOS) error {
	return o.Cloud.PublishString(topic, payload, qos)
}
