from core.aochat.BaseModule import BaseModule
from core.chat_blob import ChatBlob
from core.command_param_types import Any
from core.db import DB
from core.decorators import instance, command
from core.lookup.character_service import CharacterService
from core.lookup.pork_service import PorkService
from core.private_channel_service import PrivateChannelService
from core.setting_service import SettingService
from core.text import Text
from core.igncore import IgnCore
from core.util import Util
from modules.core.accounting.services.account_service import AccountService


@instance()
class MassinviteController(BaseModule):
    NO_RAID_RUNNING_RESPONSE = "No raid is running."

    def __init__(self):
        self.count = 0

    def inject(self, registry):
        self.bot: IgnCore = registry.get_instance("bot")
        self.db: DB = registry.get_instance("db")
        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.util: Util = registry.get_instance("util")
        self.pork: PorkService = registry.get_instance("pork_service")
        self.private_channel_service: PrivateChannelService = registry.get_instance("private_channel_service")
        self.account_service: AccountService = registry.get_instance("account_service")

    @command(command="massinvite",
             params=[Any("text")],
             description="Send a Massmessage combined with a massinvite",
             access_level="leader")
    def mass_invite(self, request, msg):
        if not self.raid:
            return self.NO_RAID_RUNNING_RESPONSE
        main = ""
        blob = ""
        spam = [self.format_subtile_spam(
            f"<highlight>{request.sender.name}</highlight> invited you to join a raid: <yellow>{msg}</yellow>"),
            self.format_spam(f"<highlight>{request.sender.name}</highlight> invited you to join a raid:\n"
                             f"<red>{msg}</red>")]
        self.bot.send_private_channel_message(spam[1])
        invites = self.account_service.get_all_members(online_only=True)
        request.reply(f"Attempting to send {len(invites)} Raid invites....")
        for player in invites:
            if player.main != main:
                main = player.main
                blob += f"\n<notice>{self.character_service.resolve_char_to_name(main)}<notice> as \n"
            blob += self.handle_player(player, spam, True)

        msg = ChatBlob("Info", blob)
        msg.page_prefix = f"{self.count} Massinvites sent! ["
        msg.page_postfix = "]"
        self.count = 0
        if request.channel == "msg":
            self.bot.send_mass_message(request.sender.char_id, msg)
        else:
            return msg

    @command(command="massmessage", params=[Any("text")], description="Send a Massmessage to all online players",
             access_level="leader")
    def mass_message(self, request, msg):
        # if not self.raid:
        #     return self.NO_RAID_RUNNING_RESPONSE
        main = ""
        blob = ""
        spam = [self.format_subtile_spam(
            f"<highlight>{request.sender.name}</highlight> sent you a message: <yellow>{msg}</yellow>"),
            self.format_spam(f"<highlight>{request.sender.name}</highlight> sent you a message:\n"
                             f"<red>{msg}</red>")]
        self.bot.send_private_channel_message(spam[1])
        invites = self.account_service.get_all_members(online_only=True)
        request.reply(f"Attempting to send {len(invites)} Massmessage's...")
        for player in invites:
            if player.main != main:
                main = player.main
                blob += f"\n<notice>{self.character_service.resolve_char_to_name(main)}<notice> as \n"
            blob += self.handle_player(player, spam, False)

        msg = ChatBlob("Info", blob)
        msg.page_prefix = f"{self.count} Massmessage's have been sent! ["
        msg.page_postfix = "]"
        self.count = 0
        if request.channel == "msg":
            self.bot.send_mass_message(request.sender.char_id, msg)
        else:
            return msg

    def handle_player(self, user, msg, invite=False):
        pg = " [<green>PG</green>]" if self.private_channel_service.in_private_channel(
            user.char_id) else " [<red>MSG sent</red>]"
        if not self.private_channel_service.in_private_channel(user.char_id):
            count = 0
            if user.raid_spam == 1:
                if user.subtile_spam == 1:
                    self.bot.send_mass_message(user.char_id, msg[0])
                else:
                    self.bot.send_mass_message(user.char_id, msg[1])
                count += 1
            if user.raid_invite == 1 and invite:
                self.private_channel_service.invite(user.char_id)
                count += 1
            if count == 0:
                return ""
            self.count += 1
        return f"<tab>{self.util.get_prof_icon(user.profession)} " \
               f"({self.text.zfill(user.level, 220)}/<green>{self.text.zfill(user.ai_level, 30)}</green>) " \
               f"<{user.faction.lower()}>{user.name}</{user.faction.lower()}> " \
               f"[<{user.faction.lower()}>{user.org_name}</{user.faction.lower()}> - " \
               f"<highlight>{user.org_rank_id + 1}</highlight>]{pg}\n"

    def format_spam(self, msg):
        return f"\n" \
               f"<yellow>────────[ Raid invite ]────────</yellow>\n" \
               f"{msg}\n" \
               f"<yellow>────────[ Raid invite ]────────</yellow>"

    def format_subtile_spam(self, msg):
        return f"[ Raid invite ] {msg}"
