package race

import (
	"fmt"
	"server/GoUtil"
	raceCfg "server/conf/race"
	"server/game/mod/item"
)

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

type Opponent struct {
	Id       int
	Type     int
	Image    int
	Progress int
}

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

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")
	}
	MaxPass := raceCfg.GetMaxPass(r.Id)
	if r.Rank != 1 || r.Pass > MaxPass {
		r.Pass = 1
	}
	r.Rank = 0
	r.StartTime = GoUtil.Now()
	Opponent := make([]*Opponent, 0)
	OpponentNum := raceCfg.GetRaceNum(r.Pass)
	for i := 1; i < OpponentNum; i++ {
		Opponent = append(Opponent, randOpponent(i))
	}
	r.Opponent = Opponent
	return nil
}

func (r *RaceMod) AddCoin(Num int) {
	if r.StartTime == 0 {
		return
	}
	r.Progress += Num
	Need := raceCfg.GetRaceNeed(r.Pass)
	if r.Progress >= Need && r.Rank == 0 {
		r.EndTime = GoUtil.Now()
		Rank := 1
		for _, v := range r.Opponent {
			if v.Progress >= r.Progress {
				Rank++
			}
		}
		r.Rank = Rank
	}
}

func (r *RaceMod) GetReward() ([]*item.Item, error) {
	if r.EndTime == 0 {
		return nil, fmt.Errorf("the game is not over")
	}

	if r.Rank != 1 {
		return nil, fmt.Errorf("you are not the first")
	}
	Cd := raceCfg.GetCD(r.Id)
	if r.Rank != 1 {
		return nil, fmt.Errorf("you are not the first")
	}
	Items := make([]*item.Item, 0)
	Reward := raceCfg.GetReward(r.Id)
	Items = append(Items, Reward...)
	if r.EndTime-r.StartTime < int64(Cd) {
		ExtraReward := raceCfg.GetExtraReward(r.Id)
		Items = append(Items, ExtraReward...)
	}
	r.Pass++
	MaxPass := raceCfg.GetMaxPass(r.Id)
	if r.Pass > MaxPass {
		r.Pass = 1
	}
	r.StartTime = 0
	r.EndTime = 0
	r.Progress = 0
	r.Opponent = nil
	return Items, nil
}

func randOpponent(Id int) *Opponent {
	return &Opponent{
		Id:    Id,
		Type:  GoUtil.RandNum(1, 3),
		Image: GoUtil.RandNum(1, 3),
	}
}
