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


@instance()
class PocketbossController:
    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 pre_start(self):
        self.db.load_sql_file(self.module_dir + "/" + "pocketboss.sql", pre_optimized=True)
        self.db.create_view("pocketboss")
        self.db.load_sql_file(self.module_dir + "/" + "pocketboss_loot.sql", pre_optimized=True)
        self.db.create_view("pocketboss_loot")

    def start(self):
        self.command_alias_service.add_alias("pb", "pocketboss")

    @command(command="pocketboss", params=[Any("search")], access_level="member",
             description="Show information about a pocketboss")
    def pocketboss_cmd(self, _, search):
        data = self.search_for_pocketboss(search)

        num = len(data)
        if num == 1:
            row = data[0]
            blob = f"Location: <highlight>{row.long_name}, {row.location}</highlight>\n"
            blob += f"Found on: <highlight>{row.mob_type}, Level {row.level:d}</highlight>\n\n"
            symbs = self.db.query("SELECT a.* FROM pocketboss_loot p "
                                  "LEFT JOIN aodb a ON p.item_id = a.highid WHERE pocketboss_id = ? "
                                  "ORDER BY a.highql DESC, a.name", [row.id])
            for symb in symbs:
                blob += f"{self.text.make_item(symb.lowid, symb.highid, symb.highql, symb.name)} ({symb.highql:d})\n"

            return ChatBlob(f"Remains of {row.name}", blob)

        else:
            blob = ""
            for row in data:
                blob += self.text.make_tellcmd(row.name, f"pocketboss {row.name}") + "\n"

            return ChatBlob(f"Pocketboss Search Results ({num:d})", blob)

    def search_for_pocketboss(self, search):
        row = self.db.query_single("SELECT p1.*, p2.long_name FROM pocketboss p1 "
                                   "LEFT JOIN playfields p2 ON p1.playfield_id = p2.id "
                                   "WHERE name LIKE ?",
                                   [search])
        if row:
            return [row]

        return self.db.query("SELECT p1.*, p2.long_name FROM pocketboss p1 "
                             "LEFT JOIN playfields p2 ON p1.playfield_id = p2.id "
                             "WHERE name <EXTENDED_LIKE=0> ? ORDER BY name",
                             [search], extended_like=True)
