from random import choice

from xbotlib import Bot


class GlossBot(Bot):
    """Building a shared glossary together.

    A glossary is "an alphabetical list of terms in a particular domain of
    knowledge with the definitions for those terms."

    This bot reacts to commands which insert, list or delete items from a
    shared glossary when summoned in a group chat. This bot makes use of
    persistent storage so the glossary is always there even if the bot goes
    away.
    """

    help = """
    I help build a shared glossary
      glossbot: @add <entry> - <definition>
      glossbot: @rm <entry>
      glossbot: @rand
      glossbot: @ls
    """

    def group(self, message):
        """Handle glossary commands."""
        if "@add" in message.content:
            try:
                parsed = self.parse_add(message)
                self.add(*parsed, room=message.room)
            except Exception:
                response = f"Couldn't understand '{message.content}'?"
                self.reply(response, room=message.sender)
        elif "@rm" in message.content:
            try:
                parsed = message.content.split("@rm")[-1].strip()
                self.rm(parsed, room=message.room)
            except Exception:
                response = f"Couldn't understand '{message.content}'?"
                self.reply(response, room=message.sender)
        elif "@rand" in message.content:
            self.rand(room=message.room)
        elif "@ls" in message.content:
            self.ls(room=message.room)
        else:
            self.log.info(f"{message.text} not recognised as glossbot command")

    def parse_add(self, message):
        """Parse the add command syntax."""
        try:
            replaced = message.content.replace("@add", "")
            return [s.strip() for s in replaced.split("-", 1)]
        except ValueError:
            self.log.error(f"Failed to parse {message.content}")

    def add(self, entry, definition, **kwargs):
        """Add a new entry."""
        self.db[entry] = definition
        self.reply("Added ✌️", **kwargs)

    def rand(self, **kwargs):
        """List a random entry."""
        if not self.db.keys():
            self.reply("Glossary is empty 🙃️", **kwargs)
            return

        entry = choice(list(self.db.keys()))
        self.reply(f"{entry} - {self.db[entry]}", **kwargs)

    def ls(self, **kwargs):
        """List all entries."""
        if not self.db.keys():
            self.reply("Glossary is empty 🙃️", **kwargs)
            return

        for entry in sorted(self.db.keys()):
            self.reply(f"{entry} - {self.db[entry]}", **kwargs)

    def rm(self, entry, **kwargs):
        """Remove an entry."""
        if entry not in self.db.keys():
            self.reply(f"{entry} doesn't exist?", **kwargs)
            return

        self.db.pop(entry)
        self.reply("Removed ✌️", **kwargs)


GlossBot()