from core.chat_blob import ChatBlob
from core.command_param_types import Any
from core.decorators import instance, command


@instance()
class SymbiantController:
    def __init__(self):
        pass

    def inject(self, registry):
        self.db = registry.get_instance("db")
        self.text = registry.get_instance("text")
        self.command_alias_service = registry.get_instance("command_alias_service")

    def start(self):
        self.command_alias_service.add_alias("symb", "symbiant")
        self.command_alias_service.add_alias("symbs", "symbiant")
        self.command_alias_service.add_alias("symbiants", "symbiant")

    @command(command="symbiant", params=[Any("search")], access_level="member",
             description="Show information about symbiants")
    def symbiant_cmd(self, _, search):
        data = self.search_for_symbiant(search)

        blob = ""
        for row in data:
            blob += f"{self.text.make_item(row.lowid, row.highid, row.highql, row.name)} ({row.highql:d})\n"
            blob += f"Found on {self.text.make_tellcmd(row.pocketboss_name, f'pocketboss {row.pocketboss_name}')}\n\n"

        return ChatBlob(f"Symbiant Search Results ({len(data):d})", blob)

    def search_for_symbiant(self, search):
        parts = " ".join((map(self.replacements, search.split(" "))))

        return self.db.query("SELECT a.*, p2.name AS pocketboss_name FROM pocketboss_loot p "
                             "LEFT JOIN aodb a ON p.item_id = a.highid "
                             "LEFT JOIN pocketboss p2 ON p.pocketboss_id = p2.id "
                             "WHERE a.name <EXTENDED_LIKE=0> ? "
                             "ORDER BY a.highql DESC, a.name", [parts], extended_like=True)

    def replacements(self, part):
        if part == "eye":
            return "ocular"
        elif part == "head":
            return "brain"
        elif part == "rarm":
            return "right arm"
        elif part == "larm":
            return "left arm"
        elif part == "rwrist":
            return "right wrist"
        elif part == "lwrist":
            return "left wrist"
        elif part == "rhand":
            return "right hand"
        elif part == "lhand":
            return "left hand"
        elif part == "leg" or part == "legs":
            return "thigh"
        else:
            return part
