package models

import (
	"errors"
	"fmt"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
)

type MqttClient struct {
	Client MQTT.Client
}

// bl是否保留在服务器 true为保留
func (class *MqttClient) PublishText(username, passwd, clientId, publish, payload string, qos int, bl bool) error {
	opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
	opts.SetUsername(username)
	opts.SetPassword(passwd)
	opts.SetClientID(clientId)
	opts.SetDefaultPublishHandler(func(c MQTT.Client, m MQTT.Message) {
		fmt.Println(m.Topic())
		fmt.Println(m.Payload())
	})
	class.Client = MQTT.NewClient(opts)
	//连接并等待连接成功
	if token := class.Client.Connect(); token.Wait() && token.Error() != nil {
		if token.WaitTimeout(3 * time.Second) {
			return errors.New("连接失败,参数错误")
		}
		panic(token.Error())
	}

	//等待发布成功 true代表订阅该主题就算是离线,只要上线就能收到(消息保存在服务器)
	if token := class.Client.Publish(publish, byte(qos), bl, payload); token.Wait() && token.Error() != nil {
		if token.WaitTimeout(3 * time.Second) {
			return errors.New("发布失败")
		}
		panic(token.Error())
	}
	class.Client.Disconnect(250)
	return nil
}

// 系统MQTT接收消息,邮件提示站长
func (class *MqttClient) SystemSubscribeToEmail() {
	username := "system"
	passwd := "0xvBYVdYOFLGlSFuJNtAJ+Uw=="
	clientId := "email"
	topic := "home/system/email"
	opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
	opts.SetUsername(username)
	opts.SetPassword(passwd)
	opts.SetClientID(clientId)
	opts.SetDefaultPublishHandler(func(c MQTT.Client, m MQTT.Message) {
		fmt.Println(m.Topic())
		fmt.Println(m.Payload())
	})
	class.Client = MQTT.NewClient(opts)
	//连接并等待连接成功
	if token := class.Client.Connect(); token.Wait() && token.Error() != nil {
		if token.WaitTimeout(3 * time.Second) {
			return
		}
		panic(token.Error())
	}

	class.Client.Subscribe(topic, byte(1), func(c MQTT.Client, m MQTT.Message) {
		mail := XyzMail{}
		temp := string(m.Payload())
		mail.To("282246101@qq.com").Title("MQTT邮件提示").Body(temp).Send()
	})
}
