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 (
	RankSeasonIdDBName   = "log"
	RankSeasonIdCollName = "log_rankseasonid"
	RankSeasonIdColError = errors.New("RankSeasonId collection open failed")
)

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

type RankSeasonIdSvc struct {
}

func (svc *RankSeasonIdSvc) Upsert(args *model.RankSeasonId, ret *bool) error {
	cc := RankSeasonIdCollection(args.Platform)
	if cc == nil {
		return RankSeasonIdColError
	}
	_, err := cc.Upsert(bson.M{"platform": args.Platform}, args)
	if err != nil {
		logger.Logger.Error("RankSeasonIdSvc.Upsert is err: ", err)
		return err
	}
	*ret = true
	return nil
}

func FindRankSeason(platform string) (*model.RankSeasonId, error) {
	fc := RankSeasonIdCollection(platform)
	if fc == nil {
		return nil, RankSeasonIdColError
	}
	var ret model.RankSeasonId
	err := fc.Find(bson.M{"platform": platform}).One(&ret)
	if err != nil && !errors.Is(err, mgo.ErrNotFound) {
		logger.Logger.Error("RankSeasonIdSvc.FindOne is err: ", err)
		return nil, err
	}
	return &ret, nil
}

func (svc *RankSeasonIdSvc) FindOne(args *model.RankSeasonId, ret *model.RankSeasonIdRet) error {
	r, err := FindRankSeason(args.Platform)
	ret.MsId = r
	return err
}

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