package kafkaMiddleware

import (
	"context"
	"server/conf"
	"server/pkg/github.com/name5566/leaf/log"
	"time"

	"github.com/segmentio/kafka-go"
)

var KafkaMod *kafka.Conn
var topic string

func init() {
	topic = conf.Server.GameName
	partition := 0

	// 连接至Kafka集群的Leader节点
	conn, err := kafka.DialLeader(context.Background(), "tcp", "kafka-server:9092", topic, partition)
	if err != nil {
		log.Debug("kafka.DialLeader err: %v", err)
		go reconnectKafka()
		return
	}
	log.Release("Reconnected to Kafka")
	KafkaMod = conn
}

func reconnectKafka() {
	partition := 0
	WaitTime := 5
	for {
		WaitTime--
		if WaitTime <= 0 {
			log.Debug("Reconnected to Kafka failed")
			return
		}
		conn, err := kafka.DialLeader(context.Background(), "tcp", "kafka-server:9092", topic, partition)
		if err == nil {
			KafkaMod = conn
			log.Debug("Reconnected to Kafka")
			break
		}
		time.Sleep(time.Second)
		log.Debug("kafka.DialLeader retry err: %v", err)
	}
}

func SendMsg(key, value []byte) error {
	if KafkaMod == nil {
		return nil
	}
	_, err := KafkaMod.WriteMessages(kafka.Message{
		Topic: topic,
		Key:   key,
		Value: value,
	})
	if err != nil {
		log.Debug("WriteMessages err: %v", err)
		reconnectKafka()
	}
	return err
}
