package srvdata

import (
	"sort"

	"mongo.games.com/game/protocol/server"
)

var RankLevelMgr = &RankLevel{
	RankType: map[int32][]*server.DB_RankLevel{},
}

type RankLevel struct {
	RankType map[int32][]*server.DB_RankLevel
}

func (r *RankLevel) Load(fileFullPath string) error {
	r.RankType = make(map[int32][]*server.DB_RankLevel)
	for _, v := range PBDB_RankLevelMgr.Datas.GetArr() {
		r.RankType[v.RankType] = append(r.RankType[v.RankType], v)
	}

	for _, v := range r.RankType {
		sort.Slice(v, func(i, j int) bool {
			return v[i].Score < v[j].Score
		})
	}

	return nil
}

func (r *RankLevel) Reload(fileFullPath string) error {
	return r.Load(fileFullPath)
}

func (r *RankLevel) GetRankLevel(rankType int32, score int64) int32 {
	// 没有配置排名
	if len(r.RankType) == 0 {
		return 0
	}

	// 没有配置该类型的排名
	if _, ok := r.RankType[rankType]; !ok {
		return 0
	}

	// 遍历排名
	var level int32
	for _, v := range r.RankType[rankType] {
		if score < v.Score {
			return v.Level
		}
		level = v.Level
	}
	return level
}

func (r *RankLevel) GetNewScore(score int64) int64 {
	if score <= 10000 {
		return score
	}
	return score/2 + 5000
}

func init() {
	DataMgrAfter.RegisterLoader("DB_RankLevel.dat", RankLevelMgr)
}
