from core.aochat import server_packets
from core.conn import Conn
from core.decorators import instance, command, event
from core.logger import Logger
from modules.standard.online.online_controller import OnlineController


@instance(name="online_controller", override=True)
class OrgOnlineController(OnlineController):
    MESSAGE_SOURCE = 'RELAY_LOGGER'

    def __init__(self):
        super().__init__()

    def inject(self, registry):
        super().inject(registry)
        self.logger = Logger('relay')
        self.character_service = registry.get_instance("character_service")
        self.event_service = registry.get_instance("event_service")

    @event("connect", 'Add bots as members')
    def connect_event(self, _, _1):
        for bot in self.db.query('SELECT * FROM account where disabled = 0'):
            self.buddy_service.add_buddy(bot.char_id, 'member')

    @command(command="online", params=[],
             description="shows online players",
             access_level="member")
    def online_all_cmd(self, request):
        query = "and channel_id IN (1, 2) "
        params = [self.bot.name, self.bot.get_char_id()]
        blob = self.online_display.format_by_channel_prof(query, params)
        return self.online_display.format_blob(blob)

    def pre_start(self):
        super().pre_start()
        self.bot.register_packet_handler(server_packets.PrivateChannelClientJoined.id,
                                         self.handle_private_channel_client_joined)
        self.bot.register_packet_handler(server_packets.PrivateChannelClientLeft.id,
                                         self.handle_private_channel_client_left)
        self.bot.register_packet_handler(server_packets.PrivateChannelMessage.id,
                                         self.handle_private_channel_message)

    def handle_private_channel_message(self, conn: Conn, packet: server_packets.PrivateChannelMessage):
        char_name = self.character_service.get_char_name(packet.char_id)
        if packet.private_channel_id == conn.char_id:
            self.logger.log_chat(conn, "PG", char_name, packet.message)

    def handle_private_channel_client_joined(self, conn: Conn, packet: server_packets.PrivateChannelClientJoined):
        char_name = self.character_service.get_char_name(packet.char_id)
        if packet.private_channel_id == conn.char_id:
            self.logger.log_chat(conn, "PG", None, f"{char_name} joined the channel.")

    def handle_private_channel_client_left(self, conn: Conn, packet: server_packets.PrivateChannelClientLeft):
        char_name = self.character_service.get_char_name(packet.char_id)
        if packet.private_channel_id == conn.char_id:
            self.logger.log_chat(conn, "PG", None, f"{char_name} left the channel.")
