package mq

import (
	"encoding/json"
	"mongo.games.com/game/dbproxy/svc"
	"mongo.games.com/game/model"
	"mongo.games.com/game/mq"
	"mongo.games.com/goserver/core"
	"mongo.games.com/goserver/core/basic"
	"mongo.games.com/goserver/core/broker"
	"mongo.games.com/goserver/core/broker/rabbitmq"
	"mongo.games.com/goserver/core/logger"
)

func init() {
	// 排位排行榜
	mq.RegisterSubscriber(model.MQRankSeason, func(e broker.Event) (err error) {
		msg := e.Message()
		if msg != nil {
			defer func() {
				if err != nil {
					mq.BackUp(e, err)
				}

				e.Ack()

				recover()
			}()

			var log model.PlayerRankScore
			err = json.Unmarshal(msg.Body, &log)
			if err != nil {
				return
			}

			logger.Logger.Tracef("SubscriberPlayerRankScore: %+v", log)

			core.CoreObject().SendCommand(basic.CommandWrapper(func(o *basic.Object) error {
				err := svc.RankSeasonUpsert(&log)
				if err != nil {
					logger.Logger.Errorf("RankSeasonUpsert err: %v", err)
				}
				return nil
			}), true)

			return
		}
		return nil
	}, broker.Queue(model.MQRankSeason), broker.DisableAutoAck(), rabbitmq.DurableQueue())

	// 金币榜
	mq.RegisterSubscriber(model.MQRankPlayerCoin, func(e broker.Event) (err error) {
		msg := e.Message()
		if msg != nil {
			defer func() {
				if err != nil {
					mq.BackUp(e, err)
				}

				e.Ack()

				recover()
			}()

			var log model.RankPlayerCoin
			err = json.Unmarshal(msg.Body, &log)
			if err != nil {
				return
			}

			logger.Logger.Tracef("SubscriberRankPlayerCoin: %+v", log)

			core.CoreObject().SendCommand(basic.CommandWrapper(func(o *basic.Object) error {
				err := svc.RankPlayerCoinUpsert(&log)
				if err != nil {
					logger.Logger.Errorf("RankPlayerCoinUpsert err: %v", err)
				}
				return nil
			}), true)

			return
		}
		return nil
	}, broker.Queue(model.MQRankPlayerCoin), broker.DisableAutoAck(), rabbitmq.DurableQueue())
}
