package quest

import (
	"fmt"
	"server/GoUtil"
	"server/msg"
	"strconv"
	"strings"
)

const (
	QUEST_STATUS_UNFINISH = 0
	QUEST_STATUS_FINISH   = 1
	QUEST_STATUS_REWARD   = 2
)

const (
	TRIGGER_LABEL_MERGELVTIME = "MergeLvTime"
	TRIGGER_LABEL_FINISHORDER = "FinishOrder"
	TRIGGER_LABEL_ENERGY      = "Energy"
	TRIGGER_LABEL_MERGETIME   = "MergeTime"
)

type QuestProgress struct {
	Label  string
	Num    int
	Target int
	Status bool
	A      []interface{}
}

type Trigger struct {
	Label string
	A     []interface{}
}

func ParseQuest(s string) (QuestProgress, error) {
	sArr := strings.Split(s, "=")
	if len(sArr) < 2 {
		return QuestProgress{}, fmt.Errorf("quest string not legel")
	}
	target, _ := strconv.Atoi(sArr[1])
	return QuestProgress{
		Label:  sArr[0],
		Target: target,
		A:      GoUtil.ToInterfaceSlice(sArr[2:]),
	}, nil
}

func TriggerQuestProgress(q *QuestProgress, Tr *Trigger) bool {
	if q.Label != Tr.Label {
		return false
	}
	if q.Status {
		return false
	}

	switch q.Label {
	case TRIGGER_LABEL_ENERGY: // 消耗x能量
		AddNum := Tr.A[0].(int)
		q.Num += AddNum
		if q.Num >= q.Target {
			q.Num = q.Target
			q.Status = true
		}

	case TRIGGER_LABEL_MERGELVTIME: // 合成x级棋子y次
		Lv, _ := Tr.A[0].(int)
		TargetLv, _ := strconv.Atoi(q.A[0].(string))
		if TargetLv == Lv {
			q.Num += 1
			if q.Num >= q.Target {
				q.Num = q.Target
				q.Status = true
			}
		}
	case TRIGGER_LABEL_MERGETIME, // 合成x次
		TRIGGER_LABEL_FINISHORDER: // 完成x次订单
		q.Num += 1
		if q.Num >= q.Target {
			q.Num = q.Target
			q.Status = true
		}
	}
	return true
}

func QuestProgressToMsg(quest *QuestProgress) *msg.QuestProgress {
	Param := 0
	if len(quest.A) > 0 {
		Param, _ = strconv.Atoi(quest.A[0].(string))
	}
	return &msg.QuestProgress{
		Label:  quest.Label,
		Num:    int32(quest.Num),
		Target: int32(quest.Target),
		Status: quest.Status,
		Param:  int32(Param),
	}
}
