import random
import re

from core.conn import Conn
from core.db import DB
from core.decorators import instance
from core.logger import Logger
from core.lookup.character_service import CharacterService
from core.setting_service import SettingService
from core.text import Text
from core.igncore import IgnCore


@instance("DingController")
class DingController:
    axp = re.compile(
        r"ICC planet-wide announcement: (.+) has been awarded the highest honorary rank for "
        r"outstanding dedication to the defence of Rubi-Ka.")
    xp = re.compile(
        r"You feel the core of your being shift, as the source makes room for a divine presence. "
        r"'(.+)' has reached enlightenment.")

    text_options_xp = ["Congratz! You have reached the end of the line! NO MORE FUN FOR YOU! :P",

                       "Holy shit, you finally made it! What an accomplishment... Congratulations "
                       "<font color=#FF1493>{name}</font>, for reaching a level reserved for the greatest!",

                       "Damn <font color=#FF1493>{name}</font>.... I'm going to miss you a great deal, "
                       "because after this, we no longer can be together <font color=#FF1493>{name}</font>."
                       " We must part so you can continue getting your research and AI levels done! Farewell!",

                       "Hey <font color=#FF1493>{name}</font>, how was the inferno grind? "
                       "I'm glad to see you made it through, and congratulations for "
                       "finally getting the level you well deserved!",

                       "Our congratulations, to our newest <font color=#FF1493>level 220</font> member, "
                       "<font color=#FF1493>{name}</font>, for his dedication. "
                       "We present him with his new honorary rank, Chuck Norris!",

                       "Holy crap, you actually did it! Dear <font color=#FF1493>{name}</font>, "
                       "I salute you for your determination and sheer awesomeness. Congratulations, "
                       "to our newest <font color=#FF1493>level 220</font> member!"]

    text_options_axp = ["Congratz! You have reached the end of the line! NO MORE FUN FOR YOU! :P",

                        "Holy shit, you finally made it! What an accomplishment... "
                        "Congratulations <font color=#FF1493>{name}</font>, "
                        "for reaching <green>Alien Level 30</green>!",

                        "Damn... I'm going to miss you a great deal, because after this, we no longer can be together, "
                        "<font color=#FF1493>{name}</font>. We must part so you can continue getting your research!"
                        " Farewell!",

                        "Hey <font color=#FF1493>{name}</font>, how was the <green>alien</green> grind?"
                        " I'm glad to see you made it through, "
                        "and congratulations for finally getting the level you well deserved!",

                        "Our congratulations, to our newest <green>Alien Level 30</green> member, "
                        "<font color=#FF1493>{name}</font>, for his dedication. "
                        "We present him with his new honorary rank, <yellow>Vindicator</yellow>!",

                        "Holy crap, you actually did it! Dear <font color=#FF1493>{name}</font>, "
                        "I salute you for your determination and sheer awesomeness. Congratulations, "
                        "to our newest <green>Alien Level 30</green> member!"]

    def __init__(self):
        self.logger = Logger(__name__)

    def inject(self, registry):
        self.bot: IgnCore = registry.get_instance("bot")
        self.text: Text = registry.get_instance("text")
        self.setting_service: SettingService = registry.get_instance("setting_service")
        self.character_service: CharacterService = registry.get_instance("character_service")
        self.message_hub_service = registry.get_instance("message_hub_service")
        self.db: DB = registry.get_instance("db")

    def pre_start(self):
        self.bot.register_packet_handler(36, self.handle_ding)
        self.bot.register_packet_handler(35, self.handle_ding)

    def handle_ding(self, conn: Conn, packet):
        if conn.char_id != self.bot.get_char_id():
            return
        # AXP 30
        if packet.id == 36:
            info = re.findall(self.axp, packet.message)
            if not info:
                return
            user = self.get_user(info[0])
            if not user:
                return
            self.bot.send_mass_message(user.char_id,
                                       f"<green>Game Over</green>! "
                                       f"{random.choice(self.text_options_axp).format(**user)} "
                                       f"<yellow>[{self.generate_output('AI 30')}]</yellow>",
                                       log_message=True)

        # XP 220
        if packet.id == 35:
            info = re.findall(self.xp, packet.message)
            if not info:
                return
            user = self.get_user(info[0])
            if not user:
                return
            self.bot.send_mass_message(user.char_id,
                                       f"<font color=#FF1493>Game Over</font>! "
                                       f"{random.choice(self.text_options_xp).format(**user)} "
                                       f"<yellow>[{self.generate_output('Level 220')}]</yellow>",
                                       log_message=True)

    def generate_output(self, level):
        invite = self.text.make_chatcmd("click here", "/tell <myname> discord invite",
                                        style="style='text-decoration:none'")
        sys = self.text.make_chatcmd("SYSTEM", "/tell <myname> admins",
                                     style="style='text-decoration:none'")
        blob = self.text.format_page('Info',
                                     f"<header>::: Information :::</header><br><br>"
                                     f"This automated message has been sent to you by:<br><br>"
                                     f"<header2>{self.bot.get_char_name()}</header2> <yellow>[<green>{sys}</green>]</yellow><br>"
                                     f"<header2>Reason for this Message: "
                                     f"<highlight>You dinged {level}</highlight></header2><br><br>"
                                     f"<header2>Have you joined The Alliance Discord yet? "
                                     f"If not <highlight>{invite}</highlight> to receive an invite. "
                                     f"(/tell <myname> discord invite from your Main)</header2>")
        return blob

    def get_user(self, name):
        return self.db.query_single("SELECT * FROM player where name=? and org_id in (SELECT * from orgs)", [name])
