from core.aochat.BaseModule import BaseModule
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, 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.text import Text
from core.igncore import IgnCore
from core.util import Util


# noinspection DuplicatedCode
@instance()
class BotController(BaseModule):
    bots = []
    threads = {}

    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.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.online = registry.get_instance("buddy_service")

    def pre_start(self):
        self.db.exec("CREATE TABLE IF NOT EXISTS org_bots(char_id int primary key not null, org_id int not null)")

    def start(self):
        pass

    @command(command="orgs", params=[Const("bots"), Const("add"), Character("botname")], access_level="admin",
             description="Add an bot to the bot list", sub_command="bots_mng")
    def cmd_orgs_bots_add(self, request, _, _1, bot):
        player = self.pork.request_char_info(bot.name, 5)
        if self.db.exec("INSERT IGNORE INTO org_bots(char_id, org_id) VALUES(?, ?)", [bot.char_id, player.org_id]) == 0:
            request.reply(f"The bot <highlight>{bot.name}<end> is already marked as a chatbot.")
        else:
            self.db.exec("DELETE FROM online where char_id=?", [bot.char_id])
            request.reply(f"Successfully marked <highlight>{bot.name}<end> as a chatbot.")

    @command(command="orgs", params=[Const("bots"), Const("rem"), Character("botname")], access_level="admin",
             description="Add an bot to the bot list", sub_command="bots_mng")
    def cmd_orgs_bots_rem(self, request, _, _1, bot):

        if self.db.exec("DELETE FROM org_bots WHERE char_id=?", [bot.char_id]) == 0:
            request.reply(f"<highlight>{bot.name}<end> is not a chatbot.")
        else:
            request.reply(f"Successfully removed <highlight>{bot.name}<end> as a chatbot. The character will show up in !online again after its next login.")

    @command(command="orgs",
             params=[Const("bots")],
             access_level="moderator",
             description="show all orgbots",
             sub_command="bots_show")
    def cmd_orgs_bots_show(self, _, _1):
        def format_row(query):
            bud = self.buddy_service.is_online(query["char_id"])
            buddy = "<green>O<end>" if bud == 1 else "<red>O<end>" if bud == 0 else "<grey>U<end>"
            return "- [{status}] <highlight>{name}<end> (<notice>{org_name}<end>)\n".format(**query, status=buddy)

        data = self.db.query("SELECT * FROM org_bots o LEFT JOIN player p on o.char_id = p.char_id order by p.org_name")
        blob = ""
        for row in data:
            blob += format_row(row)
        return ChatBlob("Our Orgbots", blob)
