package ticket

import (
	"fmt"
	"strconv"

	"git.lxtend.com/lixiangwuxian/qqbot/constants"
	"git.lxtend.com/lixiangwuxian/qqbot/handler"
	"git.lxtend.com/lixiangwuxian/qqbot/model"
)

func init() {
	// Register the handler with the server
	handler.RegisterHandler("提单 ", newTicket, constants.LEVEL_USER)
	handler.RegisterHelpInform("提单 [内容]", "ticket", "提单")
	handler.RegisterHandler("结单 ", doneTicket, constants.LEVEL_ROOT)
	handler.RegisterHelpInform("结单 [id]", "ticket", "结单")
}

func newTicket(msg model.Message) *model.Reply {
	id, err := storeTicket(msg.RawMsg[len("提单 "):], msg.UserId, msg.GroupInfo.GroupId)
	if err != nil {
		return &model.Reply{
			ReplyMsg:       fmt.Sprintf("提单失败: %s", err.Error()),
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	return &model.Reply{
		ReplyMsg:       fmt.Sprintf("提单成功，id为%d，可以至 https://www.lxtend.com/ticket 查看工单", id),
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func doneTicket(msg model.Message) *model.Reply {
	id, err := strconv.Atoi(msg.RawMsg[len("结单 "):])
	if err != nil {
		return &model.Reply{
			ReplyMsg:       fmt.Sprintf("结单失败: %s", err.Error()),
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	err = setTicketDone(id)
	if err != nil {
		return &model.Reply{
			ReplyMsg:       fmt.Sprintf("结单失败: %s", err.Error()),
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	return &model.Reply{
		ReplyMsg:       "结单成功",
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}
