package svc

import (
	"errors"
	"fmt"
	"net/rpc"
	"time"

	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"mongo.games.com/goserver/core/logger"

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

var (
	RankSeasonDBName   = "log"
	RankSeasonCollName = "log_rankmatch"
	RankSeasonColError = errors.New("RankSeason collection open failed")
)

func RankSeasonCollection(plt string, rankType int32) *mongo.Collection {
	s := mongo.MgoSessionMgrSington.GetPltMgoSession(plt, RankSeasonDBName)
	if s != nil {
		c, first := s.DB().C(fmt.Sprintf("%s_%d", RankSeasonCollName, rankType))
		if first {
			c.EnsureIndex(mgo.Index{Key: []string{"snid"}, Background: true, Sparse: true})
			c.EnsureIndex(mgo.Index{Key: []string{"isrobot", "seasonid", "score"}, Background: true, Sparse: true})
		}
		return c
	}
	return nil
}

func RankSeasonUpsert(args *model.PlayerRankScore) error {
	cc := RankSeasonCollection(args.Platform, args.RankType)
	if cc == nil {
		return RankSeasonColError
	}
	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("RankSeasonSvc.Upsert is err: ", err)
		return err
	}
	return nil
}

type RankSeasonSvc struct {
}

func (svc *RankSeasonSvc) Upsert(args *model.PlayerRankScore, ret *bool) error {
	err := RankSeasonUpsert(args)
	if err != nil {
		return err
	}
	*ret = true
	return nil
}

func (svc *RankSeasonSvc) FindRankSeason(args *model.FindPlayerRankSeasonListArgs, ret *model.FindPlayerRankSeasonListReply) error {
	fc := RankSeasonCollection(args.Platform, args.RankType)
	if fc == nil {
		return MatchSeasonColError
	}

	season, err := FindRankSeason(args.Platform)
	if err != nil {
		return err
	}

	if model.GameParamData.CloseRankListRobot {
		err = fc.Find(bson.M{"isrobot": false, "seasonid": season.SeasonId}).Sort("-score").Limit(model.GameParamData.RankSeasonMaxNum).All(&ret.List)
	} else {
		err = fc.Find(bson.M{"seasonid": season.SeasonId}).Sort("-score").Limit(model.GameParamData.RankSeasonMaxNum).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(RankSeasonSvc))
}
