package auth

import (
	"strconv"

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

func init() {
	authTableCreateSQL := `
		CREATE TABLE IF NOT EXISTS auth (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			qqid TEXT UNIQUE,
			role INTEGER
		);
	`
	sqlite3.TryCreateTable(authTableCreateSQL)
}

func HasPermission(qqID int64, level constants.PermissionLevel) bool {
	auth, err := getAuth(qqID)
	maxRetry := 50
	for i := 0; i < maxRetry && (err != nil); i++ {
		auth, err = getAuth(qqID)
	}
	if err != nil || auth.Qqid == "" {
		return false
	}
	return auth.Role <= level
}

func SetPermission(qqID int64, level constants.PermissionLevel) error {
	auth := Auth{
		Qqid: strconv.Itoa(int(qqID)),
		Role: level,
	}
	return setAuth(auth)
}

func TryExecHandler(msg model.Message, level constants.PermissionLevel, handler model.Handler) (reply *model.Reply) {
	if permission, err := getAuth(msg.UserId); err == nil {
		if permission.Role == constants.LEVEL_IGNORE {
			return nil
		}
	}
	if HasPermission(msg.UserId, level) {
		return handler(msg)
	}
	return &model.Reply{
		ReplyMsg:       "权限校验错误",
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}
