import re

from core.aochat.client_packets import PrivateMessage
from core.command_param_types import Const
from core.decorators import instance, setting, command, timerevent, event
from core.logger import Logger
from core.lookup.character_service import CharacterService
from core.message_hub_service import MessageHubService
from core.public_channel_service import PublicChannelService
from core.setting_service import SettingService
from core.setting_types import TextSettingType
from core.text import Text
from core.igncore import IgnCore
from core.util import Util


@instance()
class RaidSpyController:
    planned = ""

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

    def inject(self, registry):
        self.bot: IgnCore = registry.get_instance("bot")
        self.setting_service: SettingService = registry.get_instance("setting_service")
        self.character_service: CharacterService = registry.get_instance("character_service")
        self.public_channel_service: PublicChannelService = registry.get_instance("public_channel_service")
        self.util: Util = registry.get_instance("util")
        self.text: Text = registry.get_instance("text")
        self.relay_hub_service: MessageHubService = registry.get_instance("message_hub_service")

    @setting(name="raidbot-name", value="", description="The Raidbot")
    def raidbot(self):
        return TextSettingType(allow_empty=True)

    @event(event_type=IgnCore.PRIVATE_MSG_EVENT, description="update raidlist", is_enabled=False)
    def handle_raidbot_msg(self, _, textblob: PrivateMessage):
        if self.character_service.get_char_name(textblob.char_id) != self.setting_service.get_value("raidbot-name"):
            return
        tag = re.search(
            r"<font color=#.{6}><font color=#.{6}>Planned Raids last updated \w+ \d+\w+, \d+ \d+:\d+:: "
            r"<a href=\"text://(.+)\">.+</a></font></font>",
            textblob.message,
            re.DOTALL)
        if tag:
            textblob.message = tag[1]
        with open("data/latest_raids.txt", "w") as f:
            f.write(textblob.message)
        self.planned = textblob.message
        self.bot.send_org_message("Die Raids wurden geupdatet: " +
                                  self.text.format_page("Die Raids der Woche", self.planned), fire_outgoing_event=False)
        self.bot.send_private_channel_message("Die Raids wurden geupdatet: " +
                                              self.text.format_page("Die Raids der Woche", self.planned),
                                              fire_outgoing_event=False)

    @event(event_type="connect", description="update raidlist", is_enabled=False)
    def handle_log_raidlog(self, _, _1):
        try:
            with open("data/latest_raids.txt", "r") as f:
                self.planned = f.read()
        except FileNotFoundError:
            self.planned = "<center><font color=#DDDD44>:::: Planned Raids ::::" \
                           "</font></center><br><font color=#66AA66> Es sind mir leider keine Raids bekannt.</font>"

    # @command(command="raids", params=[],
    #          description="Shows planned raids", access_level="org_member")
    # def raids_list(self, request):
    #     return self.text.format_page("Die Raids der Woche", self.planned)

    @command(command="raids", params=[Const("update")],
             description="Shows planned raids", access_level="moderator", sub_command="update")
    def raids_patch(self, request, _):
        self.bot.send_private_message(self.character_service.resolve_char_to_id(self.raidbot().get_value()),
                                      "!raids",
                                      add_color=False)
        return "Das Updaten der Raidliste wurde eingeleitet... Sollte es neues geben, " \
               "Informiere ich Alle Mitglieder für dich."

    @timerevent(budatime="12h", description="Update Raid list")
    def check_for_raids(self, _, _2):
        if self.raidbot().get_value() == "":
            return
        self.bot.send_private_message(self.character_service.resolve_char_to_id(self.raidbot().get_value()),
                                      "!raids",
                                      add_color=False)
