import random
from konabot.plugins.handle_text.base import TextHandleResult, TextHandler, TextHandlerEnvironment, TextHandlerSync


class THShuffle(TextHandler):
    name: str = "shuffle"
    keywords: list = ["打乱"]

    async def handle(self, env: TextHandlerEnvironment, istream: str | None, args: list[str]) -> TextHandleResult:
        if istream is not None:
            w = istream
        elif len(args) == 0:
            return TextHandleResult(1, "使用方法：打乱 <待打乱的文本>，或者使用管道符传入待打乱的文本")
        else:
            w = args[0]
            args = args[1:]

        w = [*w]
        random.shuffle(w)
        return TextHandleResult(0, ''.join(w))


class THSorted(TextHandlerSync):
    name = "sort"
    keywords = ["排序"]

    def handle_sync(self, env: TextHandlerEnvironment, istream: str | None, args: list[str]) -> TextHandleResult:
        if istream is not None:
            w = istream
        elif len(args) == 0:
            return TextHandleResult(1, "使用方法：排序 <待排序的文本>，或者使用管道符传入待打乱的文本")
        else:
            w = args[0]
            args = args[1:]

        return TextHandleResult(0, ''.join(sorted([*w])))

