from logging import Logger
import random

from rollbot import as_command, RollbotFailure
from rollbot.injection import Config, Request


def fmt_list(nicks):
    if len(nicks) == 0:
        return "No one in teamspeak!"
    if len(nicks) == 1:
        return ("Only " if random.randint(0, 1) == 0 else "Oops all ") + nicks[0]
    return "I see the following people: " + ", ".join(nicks)


@as_command
async def teamspeak(query: Config("teamspeak.query"), req: Request, logger: Logger):
    try:
        async with req.get(query) as res:
            res.raise_for_status()
            return fmt_list((await res.json())["users"])
    except:
        logger.exception("Could not reach teamspeak")
        RollbotFailure.SERVICE_DOWN.raise_exc()


@as_command
async def teemspeem(query: Config("teamspeak.query"), req: Request, logger: Logger):
    result = await teamspeak(query, req, logger)
    for v in "aiou":
        result = result.replace(v, "e").replace(v.upper(), "E")
    return result.replace("k", "m").replace("K", "M")


@as_command
async def speamteek(query: Config("teamspeak.query"), req: Request, logger: Logger):
    return (await teamspeak(query, req, logger))[::-1]


@as_command
async def teamscream(query: Config("teamspeak.query"), req: Request, logger: Logger):
    return (await teamspeak(query, req, logger)).upper()


@as_command
async def ts(query: Config("teamspeak.query"), req: Request, logger: Logger):
    try:
        async with req.get(query) as res:
            res.raise_for_status()
            initials = [name[0] for name in (await res.json())["users"]]
            if len(initials) == 0:
                return ""
            return "i c: " + ", ".join(initials)
    except:
        logger.exception("Could not reach teamspeak")
        RollbotFailure.SERVICE_DOWN.raise_exc()
