import datetime
from typing import Any
from PySide6 import QtWidgets
from PySide6.QtWidgets import QHeaderView

from .qlogmodel import QLogModel, LogModelProxy
from .qt.messagelogger_ui import Ui_MessageLogger


class QMessageLogger(QtWidgets.QWidget, Ui_MessageLogger):
    def __init__(self, parent: Any = None, listIncomingMessages: Any = None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setupUi(self)
        # logs
        self.log_model = QLogModel()
        self.log_proxy = LogModelProxy()

        if listIncomingMessages != None:
            self.listIncomingMessages = listIncomingMessages
        self.listIncomingMessages.setModel(self.log_proxy)
        self.log_proxy.setSourceModel(self.log_model)
        self.log_model.rowsInserted.connect(self._log_entry_added)
        self.log_model.rowsInserted.connect(self._resize_log_table)


    def log(self, log_level, log_message) -> None:
        """Updates the log."""
        # get current time in correct timezone (Time.to_datetime looses that)
        now_datetime = datetime.datetime.now()
        # LOG
        # define new row and emit
        row = [
            now_datetime.strftime("%H:%M:%S"),
            log_level,
            log_message,
        ]
        self.log_model.add_entry(row)

    def _resize_log_table(self) -> None:
        """Resize log table to entries."""
        # resize columns
        self.listIncomingMessages.horizontalHeader().resizeSections(QHeaderView.ResizeToContents)
        self.listIncomingMessages.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)


    def _log_entry_added(self) -> None:
        """Triggered, whenever a new log item has been added."""
        sb = self.listIncomingMessages.verticalScrollBar()
        if sb.maximum() == sb.value():
            self.listIncomingMessages.scrollToBottom()
