package guesscolor

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

type GuessColorMod struct {
	Id       int
	Pass     int
	Opponent simplePlayer
	MapList  []map[int32]int32
	OMap     map[int32]int32
	WinTime  int
	First    bool
	Guess    int
}

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

const (
	GAME_STATUS_SUCCESS = 1
	GAME_STATUS_FAIL    = 2
)

func (g *GuessColorMod) InitData() {
	if g.MapList == nil {
		g.MapList = make([]map[int32]int32, 0)
	}
	if g.OMap == nil {
		g.OMap = make(map[int32]int32)
	}
	if g.Pass == 0 || g.WinTime == 0 {
		g.Pass = 1
		g.WinTime = guesscolorCfg.GetWinTime(g.Pass)
	}
	if g.Opponent.Name == "" {
		g.Opponent = simplePlayer{
			Name:   randnameCfg.GetRandName(),
			Face:   GoUtil.RandNum(1, 10),
			Avatar: GoUtil.RandNum(1, 10),
		}
	}
}

func (g *GuessColorMod) Login(Id int) int {
	OldId := g.Id
	if Id == 0 {
		g.Id = 0
		return 0
	}
	if g.Id == Id {
		return 0
	}
	g.Id = Id
	g.Pass = 1
	g.Opponent = simplePlayer{
		Name:   randnameCfg.GetRandName(),
		Face:   GoUtil.RandNum(1, 10),
		Avatar: GoUtil.RandNum(1, 10),
	}
	g.Guess = 0
	g.MapList = nil
	g.OMap = nil
	g.WinTime = guesscolorCfg.GetWinTime(g.Pass)
	return OldId
}

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, OMap map[int32]int32) {
	if len(Map) > 0 {
		g.MapList = append(g.MapList, Map)
		g.Guess++
	}
	g.OMap = OMap
}

// 获取失败奖励
func (g *GuessColorMod) GetLoseItem() []*item.Item {
	Items := guesscolorCfg.GetLoseItem(g.Id)
	Num := guesscolorCfg.GetPassNum(g.Pass)
	if len(g.MapList) > 0 {
		LastMap := g.MapList[len(g.MapList)-1]
		for _, v := range LastMap {
			if v > 10 {
				Num--
			}
		}
	}
	return item.MutilItem(Items, Num)
}

// 获取奖励
func (g *GuessColorMod) GetReward() ([]*item.Item, error) {
	if g.Pass == 0 {
		return nil, fmt.Errorf("not pass")
	}
	if g.Guess < g.WinTime {
		return nil, fmt.Errorf("guess process not finish")
	}
	Type := GAME_STATUS_FAIL
	if g.Guess == guesscolorCfg.GetPassNum(g.Pass) {
		Type = GAME_STATUS_SUCCESS
	}
	Item := guesscolorCfg.GetRewardItem(g.Pass, Type)
	g.Pass++
	g.Guess = 0
	g.WinTime = guesscolorCfg.GetWinTime(g.Pass)
	g.MapList = nil
	g.OMap = nil
	return Item, nil
}
