package svc

import (
	"errors"
	"net/rpc"

	"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 (
	PlayerRankSeasonDBName   = "user"
	PlayerRankSeasonCollName = "user_rankseason"
	PlayerRankSeasonColError = errors.New("PlayerRankSeason collection open failed")
)

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

type PlayerRankSeasonSvc struct {
}

func (svc *PlayerRankSeasonSvc) Upsert(args *model.PlayerRankSeason, ret *bool) error {
	c := PlayerRankSeasonCollection(args.Platform)
	if c == nil {
		return PlayerRankSeasonColError
	}
	_, err := c.Upsert(bson.M{"snid": args.SnId}, args)
	if err != nil {
		logger.Logger.Error("PlayerRankSeasonSvc.Upsert is err: ", err)
		return err
	}
	*ret = true
	return nil
}

func (svc *PlayerRankSeasonSvc) Find(args *model.FindPlayerRankSeasonArgs, ret *model.FindPlayerRankSeasonReply) error {
	c := PlayerRankSeasonCollection(args.Platform)
	if c == nil {
		return PlayerRankSeasonColError
	}
	err := c.Find(bson.M{"snid": bson.D{{"$in", args.Id}}}).All(&ret.List)
	if err != nil && !errors.Is(err, mgo.ErrNotFound) {
		logger.Logger.Error("PlayerRankSeasonSvc.Find is err: ", err)
		return err
	}
	return nil
}

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