package race

import (
	"fmt"
	"math/rand"
	raceCfg "server/conf/race"
	randnameCfg "server/conf/randname"
	"server/game/mod/item"
	GoUtil "server/game_util"
)

type RaceMod struct {
	Id        int
	Opponent  []*Opponent
	Pass      int
	StartTime int64
	EndTime   int64
	Progress  int
	Rank      int
}

type Opponent struct {
	Id       int
	Avatar   int
	Face     int
	Name     string
	Progress int
}

func (r *RaceMod) Login(Id int) int {
	OldId := r.Id
	if Id == 0 {
		r.Id = 0
		return OldId
	}
	if r.Id == Id {
		return 0
	}
	r.Id = Id
	r.Pass = 1
	r.StartTime = 0
	r.EndTime = 0
	r.Progress = 0
	r.Rank = 0
	r.Opponent = nil
	return OldId
}

// TODO 剩余AI逻辑未开发
func (r *RaceMod) ZeroUpdate(Id int) {
	r.Login(Id)
}

func (r *RaceMod) StartGame() error {
	if r.StartTime != 0 {
		return fmt.Errorf("the game has started")
	}
	r.StartTime = GoUtil.Now()
	OpponentNum := raceCfg.GetRaceNum(r.Pass)
	r.EndTime = r.StartTime + int64(raceCfg.GetCD(r.Id))
	r.Opponent = randOpponents(OpponentNum)
	r.Rank = 1
	return nil
}

func (r *RaceMod) AddCoin(Num int) {
	if r.StartTime == 0 {
		return
	}
	r.Progress += Num
}

func (r *RaceMod) GetReward() ([]*item.Item, error) {
	if r.EndTime == 0 {
		return nil, fmt.Errorf("the game is not over")
	}
	Need := raceCfg.GetRaceNeed(r.Pass)
	if r.Progress < Need {
		return nil, fmt.Errorf("not enough progress")
	}
	if r.Rank != 1 {
		return nil, fmt.Errorf("you are not the first")
	}
	var Items []*item.Item
	Items = append(Items, raceCfg.GetReward(r.Pass)...)
	Now := GoUtil.Now()
	if Now <= r.EndTime {
		Items = append(Items, raceCfg.GetExtraReward(r.Pass)...)
	}
	r.Pass++
	r.Progress -= Need
	MaxPass := raceCfg.GetMaxPass(r.Id)
	if r.Pass > MaxPass {
		r.Pass = 1
		r.StartTime = 0
		r.EndTime = 0
		r.Opponent = nil
		r.Progress = 0
	} else {
		r.StartTime = Now
		r.EndTime = Now + int64(raceCfg.GetCD(r.Id))
		r.Opponent = randOpponents(raceCfg.GetRaceNum(r.Pass))
	}

	return Items, nil
}

func randOpponents(OpponentNum int) []*Opponent {
	opponents := make([]*Opponent, 0, OpponentNum-1)
	names := randnameCfg.GetRandNames(OpponentNum)
	for i := 1; i < OpponentNum; i++ {
		opponents = append(opponents, randOpponent(i, names[i]))
	}
	return opponents
}
func randOpponent(Id int, name string) *Opponent {
	return &Opponent{
		Id:     Id,
		Name:   name,
		Face:   rand.Intn(10),
		Avatar: rand.Intn(10),
	}
}
