#!/usr/bin/env python3
import logging
import threading
from collections import deque

from server import ZordonServer

logger = logging.getLogger()

def __setup_buffer_handler():
    # lazy load GUI frameworks
    from PyQt6.QtCore import QObject, pyqtSignal

    class BufferingHandler(logging.Handler, QObject):
        new_record = pyqtSignal(str)
        flushOnClose = True

        def __init__(self, capacity=100):
            logging.Handler.__init__(self)
            QObject.__init__(self)
            self.buffer = deque(maxlen=capacity)  # Define a buffer with a fixed capacity

        def emit(self, record):
            try:
                msg = self.format(record)
                self.buffer.append(msg)  # Add message to the buffer
                self.new_record.emit(msg)  # Emit signal
            except RuntimeError:
                pass

        def get_buffer(self):
            return list(self.buffer)  # Return a copy of the buffer

    buffer_handler = BufferingHandler()
    buffer_handler.setFormatter(logging.getLogger().handlers[0].formatter)
    new_logger = logging.getLogger()
    new_logger.addHandler(buffer_handler)
    return buffer_handler


def __show_gui(buffer_handler):
    # lazy load GUI frameworks
    from PyQt6.QtWidgets import QApplication

    # load application
    app: QApplication = QApplication(sys.argv)
    if app.style().objectName() != 'macos':
        app.setStyle('Fusion')

    # configure main window
    from src.ui.main_window import MainWindow
    window: MainWindow = MainWindow()
    window.buffer_handler = buffer_handler
    window.show()

    exit_code = app.exec()

    # cleanup: remove and close the GUI logging handler before interpreter shutdown
    root_logger = logging.getLogger()
    if buffer_handler in root_logger.handlers:
        root_logger.removeHandler(buffer_handler)
    try:
        buffer_handler.close()
    except Exception:
        # never let logging cleanup throw during shutdown
        pass

    return exit_code

if __name__ == '__main__':
    import sys

    server = ZordonServer()
    server.start_server()
    __show_gui(__setup_buffer_handler())
    server.stop_server()
    sys.exit()
