package svc

import (
	"errors"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"mongo.games.com/game/dbproxy/mongo"
	"mongo.games.com/game/model"
	"mongo.games.com/goserver/core/logger"
	"net/rpc"
	"time"
)

var (
	RankPlayerCoinDBName   = "log"
	RankPlayerCoinCollName = "log_rankplayercoin"
	RankPlayerCoinColError = errors.New("RankPlayer collection open failed")
)

func RankPlayerCoinCollection(plt string) *mongo.Collection {
	s := mongo.MgoSessionMgrSington.GetPltMgoSession(plt, RankPlayerCoinDBName)
	if s != nil {
		c, first := s.DB().C(RankPlayerCoinCollName)
		if first {
			c.EnsureIndex(mgo.Index{Key: []string{"snid"}, Background: true, Sparse: true})
			c.EnsureIndex(mgo.Index{Key: []string{"coin"}, Background: true, Sparse: true})
		}
		return c
	}
	return nil
}

func RankPlayerCoinUpsert(args *model.RankPlayerCoin) error {
	cc := RankPlayerCoinCollection(args.Platform)
	if cc == nil {
		return RankPlayerCoinColError
	}
	args.UpdateTs = time.Now().Unix()
	_, err := cc.Upsert(bson.M{"snid": args.SnId}, args)
	if err != nil && !errors.Is(err, mgo.ErrNotFound) {
		logger.Logger.Error("RankPlayerCoinSvc.Upsert is err: ", err)
		return err
	}
	return nil
}

type RankPlayerCoinSvc struct {
}

func (svc *RankPlayerCoinSvc) Upsert(args *model.RankPlayerCoin, ret *bool) error {
	err := RankPlayerCoinUpsert(args)
	if err != nil {
		return err
	}
	*ret = true
	return nil
}

func (svc *RankPlayerCoinSvc) Find(args *model.FindPlayerCoinListArgs, ret *model.FindPlayerCoinListReply) error {
	fc := RankPlayerCoinCollection(args.Platform)
	if fc == nil {
		return RankPlayerCoinColError
	}

	err := fc.Find(bson.M{}).Sort("-coin").Limit(model.GameParamData.RankPlayerCoinMaxNum).All(&ret.List)
	if err != nil && !errors.Is(err, mgo.ErrNotFound) {
		logger.Logger.Error("QueryMatchSeason is err: ", err)
		return err
	}
	return nil
}

func init() {
	rpc.Register(new(RankPlayerCoinSvc))
}
