package busdriver

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// TestBus 测试接口
func TestBus() {
	MqConnect()
	//defer closeMQ()
	MqExchange()

	// 订阅主题
	err1 := SubscribeTopic("test1")
	err2 := SubscribeTopic("test2")
	err3 := SubscribeTopic("test3")
	if err1 != nil || err2 != nil || err3 != nil {
		fmt.Println("subscribe topic failed")
		return
	}

	MqStart()

	// 启动发送协程
	go func() {
		for {
			for _, subinfo := range SubInfos {
				msg := "test message:" + time.Now().Format("2006-01-02 15:04:05")
				Publish(subinfo.Topic, msg)
			}
			time.Sleep(5 * time.Second)
		}
	}()
}

// SubTopicReq 主题订阅请求
type SubTopicReq struct {
	Topic string `json:"topic" binding:"required"`
}

// MsgPublishReq 消息发送请求
type MsgPublishReq struct {
	Topic   string `json:"topic" binding:"required"`
	Content string `json:"content" binding:"required"`
}

// SubTopic 主题订阅
func SubTopic(c *gin.Context) {
	var subreq SubTopicReq
	err := c.ShouldBind(&subreq)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}

	err = SubscribeTopic(subreq.Topic)
	if err != nil {
		fmt.Println("subscribe topic failed:", err)
	}

	c.SecureJSON(http.StatusOK, 0)
}

// MsgPublish 消息发送
func MsgPublish(c *gin.Context) {
	var msgpublish MsgPublishReq
	err := c.ShouldBind(&msgpublish)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}

	err = Publish(msgpublish.Topic, msgpublish.Content)
	if err != nil {
		fmt.Println("publish topic failed", err)
	}

	c.SecureJSON(http.StatusOK, 0)
}
