"""
This plugin adds a ``/server_part`` command to leave all rooms
on a server.

Command
-------

.. glossary::

    /server_part
        **Usage:** ``/server_part [<server> [message]]``

        Leave all rooms on ``<server>``, if not provided and the current
        tab is a chatroom tab, it will leave all rooms on the current server.
        ``[message]`` can indicate a quit message.


"""
from slixmpp import JID, InvalidJID
from poezio.plugin import BasePlugin
from poezio.tabs import MucTab
from poezio.decorators import command_args_parser
from poezio.core.structs import Completion
from poezio.windows.inputs import Input


class Plugin(BasePlugin):
    def init(self) -> None:
        self.api.add_command(
            'server_part',
            self.command_server_part,
            usage='[<server> [message]]',
            short='Leave all the rooms on a server',
            help='Leave all the rooms on a sever.',
            completion=self.completion_server_part)

    @command_args_parser.quoted(0, 2, defaults=[])
    def command_server_part(self, args: list[str]) -> None:
        current_tab = self.api.current_tab()
        message = ''
        if not args:
            if not isinstance(current_tab, MucTab):
                self.core.command.help('server_part')
                return
            jid = current_tab.jid.bare
        elif len(args) == 1:
            try:
                jid = JID(args[0]).domain
            except InvalidJID:
                self.core.command.help('server_part')
                return
        else:
            try:
                jid = JID(args[0]).domain
            except InvalidJID:
                self.core.command.help('server_part')
                return
            message = args[1]

        for tab in self.core.get_tabs(MucTab):
            if tab.name.endswith(jid):
                tab.command_part(message)

    def completion_server_part(self, the_input: Input) -> Completion:
        serv_list = set()
        for tab in self.core.get_tabs(MucTab):
            if tab.joined:
                serv = tab.jid.server
                serv_list.add(serv)
        return Completion(the_input.new_completion, sorted(serv_list), 1, ' ')
