import discord as di
from slidge import FormField
from slidge.command import Command, CommandAccess, Form, TableResult
from slidge.command.categories import GROUPS
from slixmpp import JID
from slixmpp.exceptions import XMPPError

from .session import Session


class ListGuilds(Command):
    NAME = '🌐 List your discord "servers"'
    HELP = "List your discord servers and their channels"
    CHAT_COMMAND = NODE = "servers"
    ACCESS = CommandAccess.USER_LOGGED
    CATEGORY = GROUPS

    async def run(self, session, ifrom: JID, *args):
        assert isinstance(session, Session)
        guilds = sorted(session.discord.guilds, key=lambda guild: guild.name)
        return Form(
            title="Your discord servers",
            instructions="Select a server to view its text channels",
            fields=[
                FormField(
                    "guild_id",
                    "Discord servers",
                    required=True,
                    type="list-single",
                    options=[
                        {"label": g.name, "value": str(i)} for i, g in enumerate(guilds)
                    ],
                )
            ],
            handler=self.list_guilds,  # type:ignore
            handler_args=(guilds,),
        )

    @staticmethod
    async def list_guilds(
        form_values: dict[str, str], session: "Session", _ifrom, guilds: list[di.Guild]
    ):
        try:
            guild_id = int(form_values["guild_id"])
            guild = guilds[int(guild_id)]
        except (ValueError, IndexError, KeyError):
            raise XMPPError("bad-request")
        channels = []
        for c in guild.channels:
            if not isinstance(c, di.TextChannel):
                continue
            try:
                channels.append(await session.bookmarks.by_legacy_id(c.id))
            except XMPPError:
                continue
        channels.sort(key=lambda ch: ch.name)
        return TableResult(
            fields=[
                FormField("name", "Name"),
                FormField("jid", "JID", type="jid-single"),
            ],
            description=f"Text channels of server {guild}",
            items=[{"name": c.name, "jid": c.jid} for c in channels],
            jids_are_mucs=True,
        )
