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


@instance()
class OfabWeaponsController:
    def inject(self, registry):
        self.db = registry.get_instance("db")
        self.text: Text = registry.get_instance("text")
        self.items_controller = registry.get_instance("items_controller")
        self.command_alias_service = registry.get_instance("command_alias_service")

    def pre_start(self):
        self.db.load_sql_file(self.module_dir + "/sql/ofab_weapons.sql", pre_optimized=True)
        self.db.create_view("ofab_weapons")
        self.db.create_view("ofab_weapons_cost")

    def start(self):
        self.command_alias_service.add_alias("ofabweapon", "ofabweapons")

    @command(command="ofabweapons", params=[], access_level="member",
             description="Show ofab weapons")
    def ofabweapons_list_command(self, request):
        data = self.db.query("SELECT type, name FROM ofab_weapons ORDER BY name")

        blob = ""
        for row in data:
            blob += f"<pagebreak>{self.text.make_tellcmd(row.name, f'ofabweapons {row.name}')} - Type {row.type:d}\n"

        return ChatBlob("Ofab Weapons", blob)

    @command(command="ofabweapons",
             params=[Int("ql", is_optional=True), Any("weapon"), Int("ql", is_optional=True)],
             access_level="member",
             description="Show info about an ofab weapon",
             extended_description="QL is optional and can come before or after the weapon")
    def ofabweapons_show_command(self, request, ql1, weapon_name, ql2):
        weapon_name = weapon_name.capitalize()
        ql = ql1 or ql2 or 300

        weapon = self.db.query_single("SELECT type, vp FROM ofab_weapons w, ofab_weapons_cost c "
                                      "WHERE w.name LIKE ? AND c.ql = ?", [weapon_name, ql])

        if not weapon:
            return f"Could not find Ofab Weapon <highlight>{weapon_name}</highlight> " \
                   f"for QL <highlight>{ql:d}</highlight>."

        type_ql = round(ql * 0.8)
        type_link = self.text.make_tellcmd(f"Kyr'Ozch Bio-Material - Type {weapon.type:d}",
                                           f"bioinfo {weapon.type:d} {type_ql:d}")

        blob = "Upgrade with %s (minimum QL %d)\n\n" % (type_link, type_ql)

        data = self.db.query("SELECT ql FROM ofab_weapons_cost ORDER BY ql")
        for row in data:
            blob += self.text.make_tellcmd(row.ql, f"ofabweapons {weapon_name} {row.ql:d}") + " "
        blob += "\n\n"

        for i in range(1, 7):
            item = self.items_controller.find_by_name(f"Ofab {weapon_name} Mk {i:d}")
            blob += "<pagebreak>" + self.text.format_item(item)
            if i == 1:
                blob += f"  (<highlight>{weapon.vp:d}</highlight> VP)"
            blob += "\n"

        return ChatBlob(f"Ofab {weapon_name} (QL {ql:d})", blob)
