package champship

import (
	"fmt"
	champshipCfg "server/conf/champship"
	mergeDataCfg "server/conf/merge_data"
	"server/game/mod/item"
	GoUtil "server/game_util"
	"server/msg"
)

type ChampshipMod struct {
	Score      int
	Reward     int
	RankReward bool
	PreMax     int // 昨日最高档
	Max        int // 历史最高档
}

func (c *ChampshipMod) InitData() {}

// isActive 判断当前是否在冠军赛活跃时段（零点后 30 分钟内为结算期，不计分）
func (c *ChampshipMod) isActive() bool {
	return GoUtil.Now()-GoUtil.ZeroTimestamp() >= 1800
}

func (c *ChampshipMod) ZeroUpdate() {
	c.PreMax = c.Reward
	c.Score = 0
	c.Reward = 0
	c.RankReward = false
}

func (c *ChampshipMod) GetScore() int {
	return c.Score
}

func (c *ChampshipMod) GetRankReward(Rank int) ([]*item.Item, error) {
	if c.RankReward {
		return nil, fmt.Errorf("rank reward has been received")
	}
	c.RankReward = true
	return champshipCfg.GetRankReward(Rank), nil
}

func (c *ChampshipMod) AddScore(Chess []int) {
	if !c.isActive() {
		return
	}
	score := 0
	for _, v := range Chess {
		Lv := mergeDataCfg.GetLvById(v)
		ChessScore := champshipCfg.GetChessScore(Lv)
		score += ChessScore
	}
	c.Score += score
}

func (c *ChampshipMod) GetReward() []*item.Item {
	Reward, Items := champshipCfg.GetReward(c.Reward, c.Score)
	c.Reward = Reward
	c.Max = max(c.Max, c.Reward)
	return Items
}

func (c *ChampshipMod) BackData(MyRank, MyPreRank int) *msg.ResChampship {
	rankReward := 0
	if c.RankReward {
		rankReward = 2
	} else if MyPreRank > 0 {
		rankReward = 1
	}
	status := 0
	if c.isActive() {
		status = 1
	}
	return &msg.ResChampship{
		Score:      int32(c.Score),
		Reward:     int32(c.Reward),
		EndTime:    int32(GoUtil.ZeroTimestamp() + 86400),
		Period:     int32(GoUtil.GetServerOpenDay()),
		Rank:       int32(MyRank),
		RankReward: int32(rankReward),
		Status:     int32(status),
	}
}

func (c *ChampshipMod) GetH() int {
	return c.PreMax
}

func (c *ChampshipMod) GetN() int {
	return c.Max
}
