package mqtt

import (
	"server/global"
	"sync"
)

var _once sync.Once
var _mgr *Mgr

func GetMQTTMgr() *Mgr {
	_once.Do(func() {
		_mgr = _newMQTTMgr()
	})
	return _mgr
}

type Mgr struct {
	Cloud *MClient
}

func _newMQTTMgr() *Mgr {
	cfg := global.GVA_CONFIG.Mqtt
	return &Mgr{
		Cloud: NewMqttClient(cfg.Server,
			cfg.Id,
			cfg.User,
			cfg.Password,
			3000, &EmptyMqttOnline{}),
	}

}

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

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

func (o *Mgr) Publish(topic string, payload interface{}, qos QOS) error {
	return o.Cloud.Publish(topic, payload, qos)
}
