package handbook

import (
	"errors"
	"fmt"
	handbookCfg "server/conf/handbook"
	startMergeCfg "server/conf/start_merge"
	"server/game/mod/item"
	"server/msg"
)

type Handbook struct {
	BookList map[int]int `json:"BookList"`
	Collect  map[string]struct{}
}

const (
	STATUS_IDLE   = 0
	STATUS_REWARD = 1
)

func (h *Handbook) InitData() {
	if h.Collect == nil {
		h.Collect = make(map[string]struct{})
	}
	if h.BookList == nil {
		h.BookList = make(map[int]int)
		InitChess := startMergeCfg.GetInitChessList()
		for _, v := range InitChess {
			h.BookList[v] = STATUS_IDLE
		}
	}
}

// 解锁图鉴
func (h *Handbook) SetHandbook(Id int) bool {
	if Id <= 0 {
		return false
	}
	_, ok := h.BookList[Id]
	if ok {
		return false
	}
	h.BookList[Id] = STATUS_IDLE
	return true
}

// 领取图鉴奖励
func (h *Handbook) GetHandbookReward(Id int) error {
	status, ok := h.BookList[Id]
	if !ok {
		return errors.New("图鉴未解锁")
	}
	if status == STATUS_REWARD {
		return errors.New("图鉴奖励已领取")
	}
	h.BookList[Id] = STATUS_REWARD
	return nil
}

func (h *Handbook) CollectItem(Id string, AllChess []int) ([]*item.Item, error) {
	for _, v := range AllChess {
		if _, ok := h.BookList[v]; !ok {
			return nil, fmt.Errorf("图鉴未解锁")
		}
	}
	if _, ok := h.Collect[Id]; ok {
		return nil, fmt.Errorf("已经领取过该奖励")
	}
	Reward := handbookCfg.GetHandbookReward(Id)
	if Reward == nil {
		return nil, fmt.Errorf("奖励不存在")
	}
	h.Collect[Id] = struct{}{}
	return Reward, nil
}

func (h *Handbook) BackData() *msg.Handbook {
	BookList := make([]*msg.HandbookInfo, 0, len(h.BookList))
	for k, v := range h.BookList {
		BookList = append(BookList, &msg.HandbookInfo{
			ChessId: int32(k),
			Status:  int32(v),
		})
	}
	Collect := make([]string, 0, len(h.Collect))
	for k := range h.Collect {
		Collect = append(Collect, k)
	}
	return &msg.Handbook{
		Handbooks: BookList,
		Collect:   Collect,
	}
}
