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


# noinspection SqlCaseVsIf
@instance()
class PremadeImplantController:
    def __init__(self):
        self.slots = ["head", "eye", "ear", "rarm", "chest", "larm",
                      "rwrist", "waist", "lwrist", "rhand", "legs", "lhand", "feet"]

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

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

    @command(command="premade", params=[], access_level="member",
             description="Search for implants in the premade implant booths")
    def premade_list_cmd(self, _):
        blob = "<header2>Professions</header2>\n"
        for row in self.db.query("SELECT Name FROM Profession "
                                 "WHERE ID IN (SELECT ProfessionID FROM premade_implant) "
                                 "ORDER BY Name"):
            blob += self.text.make_tellcmd(row.Name, f"premade {row.Name}") + "\n"

        blob += "\n<header2>Slots</header2>\n"
        for row in self.db.query("SELECT * FROM ImplantType ORDER BY ImplantTypeID"):
            blob += self.text.make_tellcmd(row.Name, f"premade {row.ShortName}") + "\n"

        blob += "\n<header2>Modifiers</header2>\n"
        sql = "SELECT LongName FROM Cluster WHERE ClusterID IN " \
              "(SELECT ShinyClusterID From premade_implant UNION SELECT BrightClusterID " \
              "FROM premade_implant UNION SELECT FadedClusterID FROM premade_implant) " \
              "AND ClusterID != 0 " \
              "ORDER BY LongName"
        for row in self.db.query(sql):
            blob += self.text.make_tellcmd(row.LongName, "premade %s" % row.LongName) + "\n"

        return ChatBlob("Premade Implant", blob)

    @command(command="premade",
             params=[Any("search")],
             access_level="member",
             description="Search for implants in the premade implant booths",
             extended_description="Search can be a profession, implant slot, or modifier (ability/skill)")
    def premade_show_cmd(self, _, search):
        search = search.lower()

        prof = self.util.get_profession(search)
        slot = self.get_slot(search)
        if prof:
            blob = f"Search by profession: <highlight>{prof}</highlight>\n\n"
            results = self.search_by_profession(prof)
        elif slot:
            blob = f"Search by slot: <highlight>{slot.ShortName}</highlight>\n\n"
            results = self.search_by_slot(slot.ShortName)
        else:
            blob = f"Search by modifier: <highlight>{search}</highlight>\n\n"
            results = self.search_by_modifier(search)

        for row in results:
            blob += f"<header2>{row.profession}</header2> {row.slot} " \
                    f"<highlight>{row.ability}</highlight> {row.shiny}, {row.bright}, {row.faded}\n"

        return ChatBlob(f"Premade Implant Search Results ({len(results):d})", blob)

    def search_by_profession(self, profession):
        sql = """SELECT
                i.Name AS slot,
                p2.Name AS profession,
                a.Name AS ability,
                CASE WHEN c1.ClusterID = 0 THEN 'N/A' ELSE c1.LongName END AS shiny,
                CASE WHEN c2.ClusterID = 0 THEN 'N/A' ELSE c2.LongName END AS bright,
                CASE WHEN c3.ClusterID = 0 THEN 'N/A' ELSE c3.LongName END AS faded
            FROM premade_implant p
            JOIN ImplantType i ON p.ImplantTypeID = i.ImplantTypeID
            JOIN Profession p2 ON p.ProfessionID = p2.ID
            JOIN Ability a ON p.AbilityID = a.AbilityID
            JOIN Cluster c1 ON p.ShinyClusterID = c1.ClusterID
            JOIN Cluster c2 ON p.BrightClusterID = c2.ClusterID
            JOIN Cluster c3 ON p.FadedClusterID = c3.ClusterID
            WHERE p2.Name = ?
            ORDER BY slot"""

        return self.db.query(sql, [profession])

    def search_by_slot(self, slot):
        sql = """SELECT
                i.Name AS slot,
                p2.Name AS profession,
                a.Name AS ability,
                CASE WHEN c1.ClusterID = 0 THEN 'N/A' ELSE c1.LongName END AS shiny,
                CASE WHEN c2.ClusterID = 0 THEN 'N/A' ELSE c2.LongName END AS bright,
                CASE WHEN c3.ClusterID = 0 THEN 'N/A' ELSE c3.LongName END AS faded
            FROM premade_implant p
            JOIN ImplantType i ON p.ImplantTypeID = i.ImplantTypeID
            JOIN Profession p2 ON p.ProfessionID = p2.ID
            JOIN Ability a ON p.AbilityID = a.AbilityID
            JOIN Cluster c1 ON p.ShinyClusterID = c1.ClusterID
            JOIN Cluster c2 ON p.BrightClusterID = c2.ClusterID
            JOIN Cluster c3 ON p.FadedClusterID = c3.ClusterID
            WHERE i.ShortName = ?
            ORDER BY shiny, bright, faded"""

        return self.db.query(sql, [slot])

    def search_by_modifier(self, modifier):
        sql = """SELECT
                i.Name AS slot,
                p2.Name AS profession,
                a.Name AS ability,
                CASE WHEN c1.ClusterID = 0 THEN 'N/A' ELSE c1.LongName END AS shiny,
                CASE WHEN c2.ClusterID = 0 THEN 'N/A' ELSE c2.LongName END AS bright,
                CASE WHEN c3.ClusterID = 0 THEN 'N/A' ELSE c3.LongName END AS faded
            FROM premade_implant p
            JOIN ImplantType i ON p.ImplantTypeID = i.ImplantTypeID
            JOIN Profession p2 ON p.ProfessionID = p2.ID
            JOIN Ability a ON p.AbilityID = a.AbilityID
            JOIN Cluster c1 ON p.ShinyClusterID = c1.ClusterID
            JOIN Cluster c2 ON p.BrightClusterID = c2.ClusterID
            JOIN Cluster c3 ON p.FadedClusterID = c3.ClusterID
            WHERE c1.LongName <EXTENDED_LIKE=0> ? OR c2.LongName <EXTENDED_LIKE=1> ? OR c3.LongName <EXTENDED_LIKE=2> ?
            """

        return self.db.query(sql, [modifier, modifier, modifier], extended_like=True)

    def get_slot(self, search):
        return self.db.query_single("SELECT * FROM ImplantType WHERE Name LIKE ? OR ShortName LIKE ?", [search, search])
