package kafkaMiddleware

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

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

var KafkaMod *kafka.Writer
var topic string

func init() {
	KafkaMod = newKafkaWriter(fmt.Sprintf("%s:%s", conf.Server.KafkaHost, conf.Server.KafkaPort), conf.Server.GameName)
	log.Debug("KafkaMod init")
}

func newKafkaWriter(kafkaURL, topic string) *kafka.Writer {
	return &kafka.Writer{
		Addr:     kafka.TCP(kafkaURL),
		Topic:    topic,
		Balancer: &kafka.LeastBytes{},
	}
}

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