package auth

import (
	"log"
	"regexp"
	"strconv"

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

func init() {
	handler.RegisterFrontMatchHandler("用户权限", setUserLevel, constants.LEVEL_USER)
	handler.RegisterHelpInform("用户权限 [用户] [权限]", "用户权限", "设置用户权限。允许的权限有：根用户、管理员、信任、用户、拉黑、忽略")
}

var userLevelMap = map[string]constants.PermissionLevel{
	"根用户": constants.LEVEL_ROOT,
	"管理员": constants.LEVEL_ADMIN,
	"信任":  constants.LEVEL_TRUSTED,
	"用户":  constants.LEVEL_USER,
	"拉黑":  constants.LEVEL_BANNED,
	"忽略":  constants.LEVEL_IGNORE,
}

func setUserLevel(msg model.Message) (reply *model.Reply) {
	re := regexp.MustCompile(`\s+`)
	tokens := re.Split(msg.RawMsg, -1)
	if len(tokens) < 3 {
		return &model.Reply{
			ReplyMsg:       "参数不足",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	userText := tokens[1]
	atMsg := qq_message.AtMessage{}
	if err := atMsg.ParseMessage(userText); err == nil {
		userText = atMsg.Data.QQ
	}
	log.Println(userText)
	user, err := strconv.Atoi(userText)
	if err != nil {
		return &model.Reply{
			ReplyMsg:       "用户解析失败",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	levelText := tokens[2]
	level, ok := userLevelMap[levelText]
	if !ok {
		return &model.Reply{
			ReplyMsg:       "权限不存在",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	if err := auth.SetPermission(int64(user), level); err != nil {
		return &model.Reply{
			ReplyMsg:       "权限设置失败",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	return &model.Reply{
		ReplyMsg:       "权限设置成功",
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}
