import logging

from PyQt6.QtGui import QFont
from PyQt6.QtWidgets import QMainWindow, QVBoxLayout, QWidget, QPlainTextEdit
from PyQt6.QtCore import pyqtSignal, QObject


# Create a custom logging handler that emits a signal
class QSignalHandler(logging.Handler, QObject):
    new_record = pyqtSignal(str)

    def __init__(self):
        logging.Handler.__init__(self)
        QObject.__init__(self)

    def emit(self, record):
        msg = self.format(record)
        try:
            self.new_record.emit(msg)  # Emit signal
        except RuntimeError:
            pass


class ConsoleWindow(QMainWindow):
    def __init__(self, buffer_handler):
        super().__init__()
        self.buffer_handler = buffer_handler
        self.log_handler = None
        self.init_ui()
        self.init_logging()

    def init_ui(self):
        self.setGeometry(100, 100, 600, 800)
        self.setWindowTitle("Log Output")

        self.text_edit = QPlainTextEdit(self)
        self.text_edit.setReadOnly(True)
        self.text_edit.setFont(QFont("Courier", 10))

        layout = QVBoxLayout()
        layout.addWidget(self.text_edit)
        layout.setContentsMargins(0, 0, 0, 0)

        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

    def init_logging(self):

        self.buffer_handler.new_record.connect(self.append_log_record)
        # Display all messages that were buffered before the window was opened
        for record in self.buffer_handler.get_buffer():
            self.text_edit.appendPlainText(record)

        self.log_handler = QSignalHandler()
        # self.log_handler.new_record.connect(self.append_log_record)
        self.log_handler.setFormatter(self.buffer_handler.formatter)
        logging.getLogger().addHandler(self.log_handler)
        logging.getLogger().setLevel(logging.INFO)

    def append_log_record(self, record):
        self.text_edit.appendPlainText(record)
