package consumer

import (
	"git.quantgroup.cn/DevOps/enoch/service/conf"
	"github.com/Shopify/sarama"
	"github.com/bsm/sarama-cluster"
	"github.com/vrg0/go-common/logger"
	"os"
	"os/signal"
	"sync/atomic"
	"syscall"
)

var consumerCount int32

func AgentClusterConsumer(kafkaConf conf.KafkaConf, messageHandle MessageHandler) {
	config := cluster.NewConfig()
	config.Consumer.Return.Errors = true
	config.Consumer.Offsets.Initial = sarama.OffsetOldest
	config.Group.Return.Notifications = true

	consumer, err := cluster.NewConsumer(kafkaConf.Broker, kafkaConf.Group, []string{kafkaConf.Topic}, config)
	if err != nil {
		panic(err)
	}
	atomic.AddInt32(&consumerCount, 1)
	// trap SIGINT to trigger a shutdown.
	signals := make(chan os.Signal, 1)
	signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT, os.Interrupt)

	defer func() {
		_ = consumer.Close()
		messageHandle.Destroy()
		atomic.AddInt32(&consumerCount, -1)
		logger.Info("consumer结束")
		if consumerCount == 0 {
			os.Exit(0)
		}
	}()

	// consume errors
	go func() {
		for err := range consumer.Errors() {
			logger.Error("consume error:", err.Error())
		}
	}()

	// consume notifications
	go func() {
		for ntf := range consumer.Notifications() {
			logger.Info("Rebalanced: %+v\n", ntf)
		}
	}()

	// consume messages, watch signals
	for {
		select {
		case msg, ok := <-consumer.Messages():
			if ok {
				messageHandle.MsgProcess(string(msg.Value))
				consumer.MarkOffset(msg, "") // mark message as processed
			}
		case <-signals:
			return
		}
	}
}
