package gmdata

import (
	"encoding/json"
	"leafstalk/log"
	"os"
	"sort"
)

type KingSeasonDan struct {
	Id             int    `json:"id"`
	Type           int    `json:"type"`
	DanName        string `json:"danName"`
	DanIcon        string `json:"danIcon"`
	Count          int64  `json:"count"`
	IsReducePoints int    `json:"isReducePoints"`
	Reward         []int  `json:"reward"`
}

var (
	KingSeasonDans []*KingSeasonDan
)

type ByMasterScore []*KingSeasonDan

func (a ByMasterScore) Len() int           { return len(a) }
func (a ByMasterScore) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByMasterScore) Less(i, j int) bool { return a[i].Count < a[j].Count }

// LoadKingSeason 加载配置信息
func LoadKingSeason(confPath string) {
	loadLoadKingSeasonFile(confPath+"/"+"KingSeasonDan.json", &KingSeasonDans)
	sort.Sort(sort.Reverse(ByMasterScore(KingSeasonDans)))
}

func loadLoadKingSeasonFile(filePath string, val interface{}) {
	ptrFile, err := os.Open(filePath)
	if err != nil {
		log.Fatalln("读取json文件失败", err)
	}
	defer ptrFile.Close()

	decoder := json.NewDecoder(ptrFile)
	if err = decoder.Decode(&val); err != nil {
		log.Fatalln("loadLoadKingSeasonFile Decoder failed ", filePath, err.Error())
	}
}

// GetDanByScore 通过段位积分获取当前段位
func GetDanByScore(score int64) *KingSeasonDan {
	cnt := len(KingSeasonDans)
	i := sort.Search(cnt, func(i int) bool {
		return score >= KingSeasonDans[i].Count
	})
	if i < cnt {
		return KingSeasonDans[i]
	}
	return nil
}
