package friendTreasure

import (
	"fmt"
	"server/GoUtil"
	friendTreasureCfg "server/conf/friendTreasure"
	"server/game/mod/item"
	"server/msg"
)

type FriendTreasureMod struct {
	Star   int // 星级
	Shift  int // 挡位
	Pos    []int
	List   map[int]*msg.TreasureInfo
	List2  []int32 // 选择的好友
	Status int
}

const (
	FRIEND_TYPE_ALIVE     = 1
	FRIEND_TYPE_NOT_ALIVE = 2
)

func (f *FriendTreasureMod) InitData() {
	if f.List == nil {
		f.List = make(map[int]*msg.TreasureInfo)
	}
}

func (f *FriendTreasureMod) ZeroUpdate() {
	f.Star = 0
	f.Shift = 0
	f.Pos = nil
	f.List = make(map[int]*msg.TreasureInfo)
	f.List2 = nil
	f.Status = 0
}

func (f *FriendTreasureMod) InitGame(List []*msg.TreasureInfo, List2 []int32) {
	for _, v := range List {
		f.List[int(v.Pos)] = v
	}
	f.List2 = List2
	f.Status = 1
}

func (f *FriendTreasureMod) AddStar(Star int) {
	f.Star = min(200, f.Star+Star)
}

func (f *FriendTreasureMod) Flip(Pos int) ([]*item.Item, error) {
	if f.Status == 0 {
		return nil, fmt.Errorf("game not start")
	}
	f.Shift++
	Info := f.List[Pos]

	if Info.Type == FRIEND_TYPE_ALIVE {
		ProbMap := friendTreasureCfg.GetChestProb()
		Prob := GoUtil.RandMap(ProbMap)
		Info.Status = 1
		return friendTreasureCfg.GetChestItems(Prob), nil
	}
	Info.Status = 1
	return nil, nil
}

func (f *FriendTreasureMod) EndGame() ([]*item.Item, int, error) {
	if f.Status == 0 {
		return nil, 0, fmt.Errorf("game is over")
	}
	// f.Shift++
	ProbAdd := friendTreasureCfg.GetProbAdd(f.Shift)
	ItemNum := int(float64(f.Star) * (100.0 + float64(ProbAdd)) / 100.0)
	FriendItemNum := ItemNum / 10
	Reward := []*item.Item{
		{Id: item.ITEM_STAR_ID, Num: ItemNum},
	}
	if f.Shift == 9 {
		BigReward := friendTreasureCfg.GetBigReward()
		Reward = append(Reward, BigReward...)
	}
	f.Star = 0
	f.Shift = 0
	f.Status = 2
	return Reward, FriendItemNum, nil
}

func (f *FriendTreasureMod) NotifyStar() *msg.ResFriendTreasureStar {
	return &msg.ResFriendTreasureStar{
		Star: int32(f.Star),
	}
}

func (f *FriendTreasureMod) BackData() *msg.ResFriendTreasure {
	TreasureInfoList := make([]*msg.TreasureInfo, 0)

	for _, v := range f.List {
		TreasureInfoList = append(TreasureInfoList, v)
	}

	return &msg.ResFriendTreasure{
		Status: int32(f.Status),
		List:   TreasureInfoList,
		List2:  f.List2,
		Star:   int32(f.Star),
		Shift:  int32(f.Shift),
	}
}
