from threading import Thread

from core import command_request, sender_obj
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")

    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="bots", params=[Const("add"), Character("botname")], access_level="admin",
             description="Add an bot to the bot list")
    def bots_add_any(self, sender, _, bot):
        Thread(target=self.bots_add, args=(bot, sender)).start()

    def bots_add(self, bot: sender_obj, request: command_request):
        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("The bot <highlight>%s<end> is already marked as an chatbot." % bot.name)
        else:
            request.reply("Successfully marked <highlight>%s<end> as an chatbot." % bot.name)

    @command(command="bots",
             params=[],
             access_level="moderator",
             description="show all orgbots",
             sub_command="show")
    def bots_show_all(self, _):
        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)
