import typing

from core.buddy_service import BuddyService
from core.chat_blob import ChatBlob
from core.command_alias_service import CommandAliasService
from core.command_param_types import Const, Options, Character
from core.db import DB
from core.decorators import instance, command
from core.logger import Logger
from core.lookup.pork_service import PorkService
from core.setting_service import SettingService
from core.text import Text
from core.translation_service import TranslationService
from core.igncore import IgnCore
from core.util import Util
if typing.TYPE_CHECKING:
    from modules.core.accounting.services.account_service import AccountService
    from modules.core.discord.discord_controller import DiscordController


@instance()
class PreferenceController:

    def inject(self, registry):
        self.logger = Logger(__name__)
        self.bot: IgnCore = registry.get_instance("bot")
        self.db: DB = registry.get_instance("db")
        self.text: Text = registry.get_instance("text")
        self.util: Util = registry.get_instance("util")
        self.account_service: AccountService = registry.get_instance("account_service")
        self.pork: PorkService = registry.get_instance("pork_service")
        self.org_pork: PorkService = registry.get_instance("org_pork_service")
        self.command_alias_service: CommandAliasService = registry.get_instance("command_alias_service")
        self.buddy_service: BuddyService = registry.get_instance("buddy_service")
        self.setting_service: SettingService = registry.get_instance("setting_service")
        self.discord: DiscordController = registry.get_instance("discord_controller")
        self.job_scheduler = registry.get_instance("job_scheduler")
        self.ts: TranslationService = registry.get_instance("translation_service")
        self.getresp = self.ts.get_response

    def start(self):
        self.command_alias_service.add_alias("prefs", "preferences")
        self.command_alias_service.add_alias("autoinvite", "preferences set autoinvite")

    @command(command="preferences", params=[], description="View your Preferences", access_level="member")
    def show_prefs(self, request):
        account = self.account_service.get_account(request.sender.char_id)
        if not account:
            return "You dont have any preferences you could manage...."
        return ChatBlob("Your Preferences", self.get_pref_view_full(account))

    @command(command="preferences",
             params=[Const("set"),
                     Options(["news", "raidinvite", "subtilespam", "autoinvite", "raidspam"]),
                     Options(["on", "off", "yes", "no"])],
             description="Change your Preferences", access_level="member")
    def set_prefs(self, request, _, pref: str, value):
        account = self.account_service.get_account(request.sender.char_id)
        if not account:
            return "You dont have any preferences you could manage...."
        self.set_pref(request.sender.char_id, pref, 0 if value in ["off", "no"] else 1)
        return f"Your <highlight>{pref.capitalize()}</highlight> preference has been set to {value}."

    @command(command="prefadmin",
             params=[Const("set"),
                     Character("main"),
                     Options(["news", "raidinvite", "subtilespam", "autoinvite", "raidspam"]),
                     Options(["on", "off", "yes", "no"])],
             description="Change your Preferences",
             sub_command='mdf',
             access_level="admin")
    def set_pref_admin(self, _, _1, main, pref: str, value):
        self.set_pref(main.char_id, pref, 0 if value in ["off", "no"] else 1)
        return f"<highlight>{main.name}</highlight>'s <highlight>{pref.capitalize()}</highlight> " \
               f"preference has been set to {value}."

    @command(command="prefadmin", params=[Character('character')], description="View the preferences of a player", access_level="moderator")
    def show_prefadmin(self, request, char):
        if not char.char_id:
            return self.getresp("global", "char_not_found", {"char": char.name})
        account = self.account_service.get_account(char.char_id)
        if not account:
            return f"{char.name} has no preferences you could manage...."
        return ChatBlob(f"{account.name}'s Preferences", self.get_pref_view_full(account, account))

    def get_prefs(self, char_id):
        return self.account_service.get_account(char_id)

    def set_pref(self, char_id, pref, value):
        pref = "subtile_spam" if pref == "subtilespam" \
            else "raid_invite" if pref == "raidinvite" \
            else "news_spam" if pref == "news" \
            else "auto_invite" if pref == "autoinvite" \
            else 'raid_spam' if pref == "raidspam" \
            else ""

        self.db.exec(f"UPDATE account set {pref}={value} where char_id=(SELECT main from account where char_id=?)",
                     [char_id])

    def get_pref_view_small(self, prefs, owner=None):
        return f"\n" \
               f"  └ [{self._make_cmd('news', prefs.news_spam, owner)}] News  -  " \
               f"Autoinvite [{self._make_cmd('autoinvite', prefs.auto_invite, owner)}], \n" \
               f"  └ [{self._make_cmd('raidinvite', prefs.raid_invite, owner)}] Raidinvite  -  " \
               f"Massmessage [{self._make_cmd('raidspam', prefs.raid_invite, owner)}], \n" \
               f"  └ [{self._make_cmd('subtilespam', prefs.subtile_spam, owner)}] Subtilespam"

    def get_pref_view_full(self, prefs, owner=None):
        return f"\n" \
               f"<tab>└ [ {self._make_cmd('news', prefs.news_spam, owner)} ] Do you want your News on Logon? \n" \
               f"<tab>└ [ {self._make_cmd('autoinvite', prefs.auto_invite, owner)} ] Do you want to receive autoinvites? \n" \
               f"<tab>└ [ {self._make_cmd('raidinvite', prefs.raid_invite, owner)} ] Do you want to receive raidinvites? \n" \
               f"<tab>└ [ {self._make_cmd('raidspam', prefs.raid_invite, owner)} ] Do you want to receive massmessages? \n" \
               f"<tab>└ [ {self._make_cmd('subtilespam', prefs.subtile_spam, owner)} ] Do you want a subtile invite spam? \n"

    def _make_cmd(self, pref, value, owner=None):
        # ---
        # [ YES | NO ]
        if owner:
            if value == 1:
                return f"<green>YES</green> | {self.text.make_chatcmd('NO', f'/tell <myname> prefadmin set {owner.name} {pref} off')}"
            else:
                return f"{self.text.make_chatcmd('YES', f'/tell <myname> prefadmin set {owner.name} {pref} on')} | <red>NO</red>"

        if value == 1:
            return f"<green>YES</green> | {self.text.make_chatcmd('NO', f'/tell <myname> preferences set {pref} off')}"
        else:
            return f"{self.text.make_chatcmd('YES', f'/tell <myname> preferences set {pref} on')} | <red>NO</red>"
