package mq

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/astaxie/beego/cache"
	"mongo.games.com/goserver/core/broker"
	"mongo.games.com/goserver/core/broker/rabbitmq"
	"mongo.games.com/goserver/core/logger"

	"mongo.games.com/game/dbproxy/svc"
	"mongo.games.com/game/model"
	"mongo.games.com/game/mq"
)

var InviteNumCache = cache.NewMemoryCache()

func init() {
	mq.RegisterSubscriber(model.EvtBindInvite, 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.BindInvite
			err = json.Unmarshal(msg.Body, &log)
			if err != nil {
				return
			}

			// 绑定
			err = svc.BindInviteSnId(log.Platform, log.SnId, log.InviteSnId, log.Ts)
			if err != nil {
				logger.Logger.Errorf("BindInviteSnId error:%v", err)
				return err
			}

			name := fmt.Sprintf("%v", log.InviteSnId)
			b := InviteNumCache.Get(name)
			n, _ := b.(int32)
			if n > 0 {
				n++
			} else {
				n, err = svc.GetInviteNum(log.Platform, log.InviteSnId)
				if err != nil {
					logger.Logger.Errorf("BindInviteSnId error:%v", err)
					return err
				}
			}
			InviteNumCache.Put(name, n, int64(time.Hour.Seconds()))

			// 更新绑定数量
			RabbitMQPublisher.Send(model.AckBindNum, &model.BindNum{
				SnId: log.InviteSnId,
				Num:  n,
			})

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