package models

import (
	"context"
	"errors"
	"fmt"
	"net"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"syscall"

	"github.com/DrmagicE/gmqtt"
	_ "github.com/DrmagicE/gmqtt/persistence"
	"github.com/DrmagicE/gmqtt/pkg/packets"
	"github.com/DrmagicE/gmqtt/server"
	_ "github.com/DrmagicE/gmqtt/topicalias/fifo"
)

type XyzMqttServer struct {
}

func (class XyzMqttServer) Init() {

	ln, err := net.Listen("tcp", ":1883")
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	hooks := server.Hooks{
		OnAccept:       nil,
		OnStop:         nil,
		OnSubscribe:    nil,
		OnSubscribed:   nil,
		OnUnsubscribe:  nil,
		OnUnsubscribed: nil,
		OnMsgArrived:   nil,
		OnBasicAuth: func(ctx context.Context, client server.Client, req *server.ConnectRequest) error {
			//验证账号
			username := string(req.Connect.Username)
			passwd := string(req.Connect.Password)
			cid := string(req.Connect.ClientID)
			//fmt.Println(username, passwd, cid)
			bl := Db.Sql("SELECT id FROM Mqtt WHERE username=? AND passwd=? AND clientId=?", username, passwd, cid).Row()
			if bl {
				return nil
			}
			return errors.New("失败")
		},
		OnEnhancedAuth:      nil,
		OnReAuth:            nil,
		OnConnected:         nil,
		OnSessionCreated:    nil,
		OnSessionResumed:    nil,
		OnSessionTerminated: nil,
		OnDelivered:         nil,
		OnClosed:            nil,
		OnMsgDropped:        nil,
		OnWillPublish:       nil,
		OnWillPublished:     nil,
	}

	srv := server.New(
		server.WithTCPListener(ln),
		server.WithHook(hooks),
	)
	// 保留服务
	retainedService := srv.RetainedService()

	// 发布服务
	//pub := srv.Publisher()
	// 添加保留消息
	retainedService.AddOrReplace(&gmqtt.Message{
		QoS:      packets.Qos1,
		Retained: true,
		Topic:    "a/b/c",
		Payload:  []byte("retained message"),
	})

	go func() {
		signalCh := make(chan os.Signal, 1)
		signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM)
		<-signalCh
		srv.Stop(context.Background())
	}()
	err = srv.Run()
	if err != nil {
		panic(err)
	}

}
