package exec

import (
	"net/url"
	"strings"

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

func init() {
	handler.RegisterHandler("exec", runInDocker, constants.LEVEL_USER)
	handler.RegisterHelpInform("exec", "docker", "exec <command> 执行命令")
	handler.RegisterHandler("reboot", restartDocker, constants.LEVEL_USER)
	handler.RegisterHelpInform("reboot", "docker", "reboot 重启环境")
}

func runInDocker(msg model.Message) (reply *model.Reply) {
	token := util.SplitN(msg.RawMsg, 2)
	if len(token) < 2 {
		reply.ReplyMsg = "Usage: exec <command>"
		reply.FromMsg = msg
		return
	}
	decodedCMD, _ := url.QueryUnescape(token[1])
	decodedCMD = strings.ReplaceAll(decodedCMD, "&#44;", ",")
	decodedCMD = strings.ReplaceAll(decodedCMD, "&#91;", "[")
	decodedCMD = strings.ReplaceAll(decodedCMD, "&#93;", "]")
	decodedCMD = strings.ReplaceAll(decodedCMD, "&amp;", "&")
	if res, err := exec.DockerContainer.ExecCommandInContainer(decodedCMD); err != nil {
		reply.ReplyMsg = "Error: " + err.Error()
		reply.ReferOriginMsg = true
		reply.FromMsg = msg
		return
	} else {
		pos := strings.LastIndex(res, "\n")
		if pos != -1 {
			res = res[:pos-1]
		}
		reply.ReplyMsg = res
		reply.ReferOriginMsg = true
		reply.FromMsg = msg
		return
	}
}

func restartDocker(msg model.Message) (reply *model.Reply) {
	if err := exec.DockerContainer.RestartAndCleanContainer(); err != nil {
		reply.ReplyMsg = "Error: " + err.Error()
		reply.ReferOriginMsg = true
		reply.FromMsg = msg
		return
	} else {
		reply.ReplyMsg = "Restarted"
		reply.ReferOriginMsg = true
		reply.FromMsg = msg
		return
	}
}
