package main

import (
	"encoding/json"

	"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/game/common"
	"mongo.games.com/game/model"
	"mongo.games.com/game/mq"
)

func init() {
	mq.RegisterSubscriber(model.TopicProbeCoinLogAck, func(e broker.Event) (err error) {
		msg := e.Message()
		if msg != nil {
			defer func() {
				e.Ack()
				recover()
			}()

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

			//通知主线程执行后续操作
			core.CoreObject().SendCommand(basic.CommandWrapper(func(o *basic.Object) error {
				player := PlayerMgrSington.GetPlayerBySnId(log.SnId)
				if player != nil {
					player.Coin += log.RestCount
					player.SyncGameCoin(int(log.RoomId), log.SeqNo)
				}
				return nil
			}), true)
			return
		}
		return nil
	}, broker.Queue(model.TopicProbeCoinLogAck), rabbitmq.DurableQueue())

	// 绑定数量同步
	mq.RegisterSubscriber(model.AckBindNum, func(e broker.Event) error {
		msg := e.Message()
		if msg != nil {
			defer func() {
				e.Ack()
				recover()
			}()

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

			//通知主线程执行后续操作
			core.CoreObject().SendCommand(basic.CommandWrapper(func(o *basic.Object) error {
				player := PlayerMgrSington.GetPlayerBySnId(log.SnId)
				if player != nil {
					player.InviteNum = log.Num
					player.ResetTaskN(common.TaskTypeInviteNum)
					TaskSubjectSingleton.Touch(common.TaskTypeInviteNum, &TaskData{SnId: player.SnId, Num: int64(player.InviteNum)})
				}
				return nil
			}), true)
		}
		return nil
	}, broker.Queue(model.AckBindNum), rabbitmq.DurableQueue())
}
