from core.decorators import instance, event
from modules.core.private_channel.private_channel_controller import PrivateChannelController


@instance(name="private_channel_controller", override=True)
class CustomPrivateChannelController(PrivateChannelController):
    def inject(self, registry):
        super().inject(registry)

    @event("connect", "Reinvite previous raiders")
    def reinvite_all(self, _, _1):
        for user in self.reinvite:
            # For preventing help ping pong, we're disabling the message on the relay bot.
            # self.bot.send_mass_message(user, "You have been <green>reinvited</green> into my private channel "
            #                                  "after a bot restart or crash; Sorry for the inconvenience.")
            self.priv.invite(user)
        del self.reinvite

    def handle_incoming_relay_message(self, ctx):
        self.bot.send_private_channel_message(ctx.formatted_message, fire_outgoing_event=False)

    @event(event_type="member_logon", description="Send autoinvites to players logging in")
    def logon_event(self, _, data):
        if not self.bot.is_ready():
            if data.packet.char_id not in self.reinvite:
                account = data.account
                if account.disabled == 1:
                    pass
                elif account.auto_invite == 1:
                    self.reinvite.append(data.packet.char_id)
            return
        if self.private_channel_service.in_private_channel(data.packet.char_id):
            return
        account = data.account
        if account.disabled == 1:
            return
        if self.db.query_single("SELECT * from org_bots where char_id=?", [data.packet.char_id]):
            return
        if account.auto_invite == 1:
            if self.pork.get_character_info(data.packet.char_id).org_id != self.bot.public_channel_service.org_id:
                self.private_channel_service.invite(data.packet.char_id)
                # For preventing help ping pong, we're disabling the message on the relay bot.
                # self.bot.send_mass_message(data.packet.char_id, "You have been "
                #                                                 "<highlight>auto invited</highlight> "
                #                                                 "into my private channel.")
