package guesscolor

import (
	"fmt"
	"server/GoUtil"
	guesscolorCfg "server/conf/guessColor"
	randnameCfg "server/conf/randname"
	"server/game/mod/item"
)

type GuessColorMod struct {
	Id       int
	Pass     int
	Opponent simplePlayer
	Answer   map[int]int
	Progress map[int]int
	First    bool
}

type simplePlayer struct {
	Name     string
	Face     int
	Avatar   int
	Progress int
}

func (g *GuessColorMod) InitData() {
	if g.Answer == nil {
		g.Answer = make(map[int]int)
	}
	if g.Progress == nil {
		g.Progress = make(map[int]int)
	}
	if g.Opponent.Name == "" {
		g.Opponent = simplePlayer{
			Name:     randnameCfg.GetRandName(),
			Face:     GoUtil.RandNum(1, 10),
			Avatar:   GoUtil.RandNum(1, 10),
			Progress: 0,
		}
	}
}

func (g *GuessColorMod) Login(Id int) {
	if Id == 0 {
		return
	}
	if g.Id == Id {
		return
	}
	g.Id = Id
	g.Pass = 1
	g.Opponent = simplePlayer{
		Name:     randnameCfg.GetRandName(),
		Face:     GoUtil.RandNum(1, 10),
		Avatar:   GoUtil.RandNum(1, 10),
		Progress: 0,
	}
	g.Answer = make(map[int]int)
	g.Progress = make(map[int]int)
	FirstPass := guesscolorCfg.GetFirstPass(Id)
	g.Answer = FirstPass
}

func (g *GuessColorMod) ZeroUpdate(Id int) {
	g.Login(Id)
}

func (g *GuessColorMod) FirstIn() []*item.Item {
	if g.First {
		return nil
	}
	g.First = true
	return guesscolorCfg.GetFirstItem(g.Id)
}

func (g *GuessColorMod) Take(Map map[int32]int32) {
	for k, v := range Map {
		if g.Answer[int(k)] == int(v) {
			g.Progress[int(k)] = int(v)
		}
	}
}

func (g *GuessColorMod) GetLoseItem() []*item.Item {
	return guesscolorCfg.GetLoseItem(g.Id)
}

func (g *GuessColorMod) GetReward() ([]*item.Item, error) {
	if len(g.Answer) != len(g.Progress) {
		return nil, fmt.Errorf("guess color progress error")
	}
	RewardId := 1
	if g.Opponent.Progress == len(g.Answer) {
		RewardId = 2
	}
	Item := guesscolorCfg.GetRewardItem(RewardId)
	g.Pass++
	Num := guesscolorCfg.GetPassNum(g.Pass)
	ColorList := guesscolorCfg.GetJackpot()
	RandList := GoUtil.RandSliceNum(ColorList, Num)
	g.Progress = make(map[int]int)
	for k, v := range RandList {
		g.Answer[k+1] = v
	}
	return Item, nil
}
