import logging
import os
from .__prelude__ import Qt, INSARVIZ_ROOT


class LogsItemModel(Qt.QAbstractItemModel):
    def __init__(self, log_store):
        super().__init__()
        self._log_store = log_store
        self._log_store.new_record.connect(self._on_new_record)

    @Qt.Slot()
    def _on_new_record(self):
        size = len(self._log_store.records)
        self.beginInsertRows(Qt.QModelIndex(), size-1, size-1)
        self.endInsertRows()

    def rowCount(self, index):
        if index.isValid():
            return 0
        else:
            return len(self._log_store.records)
    def columnCount(self, index):
        return 4

    def parent(self, index):
        return Qt.QModelIndex()

    def headerData(self, section, orientation, role):
        if orientation == Qt.Qt.Horizontal:
            if role == Qt.Qt.ItemDataRole.DisplayRole:
                match section:
                    case 0:
                        return "Log level"
                    case 1:
                        return "Source"
                    case 2:
                        return "Function"
                    case 3:
                        return "Message"
        else:
            if role == Qt.Qt.ItemDataRole.DisplayRole:
                return str(section)
        return None

    def data(self, index, role):
        if index.isValid():
            record = self._log_store.records[index.row()]
            if role == Qt.Qt.ItemDataRole.DisplayRole:
                match index.column():
                    case 0:
                        return record.levelname
                    case 1:
                        return record.pathname.removeprefix(INSARVIZ_ROOT).removesuffix(".py").replace(os.sep, ".")+":"+str(record.lineno)
                    case 2:
                        return record.funcName
                    case 3:
                        return record.message

            if role == Qt.Qt.ItemDataRole.ForegroundRole:
                match record.levelno:
                    case logging.WARNING:
                        return Qt.QColor('orange')
                    case logging.ERROR:
                        return Qt.QColor('red')
                    case logging.DEBUG:
                        return Qt.QColor('grey')
                return None
            return None

    def index(self, row, column, parent):
        return self.createIndex(row, column, None)

class LoggerWidget(Qt.QTableView):
    def __init__(self, log_store):
        super().__init__()
        self.setModel(LogsItemModel(log_store))
        self.horizontalHeader().setStretchLastSection(True)
        self.verticalHeader().setSectionResizeMode(Qt.QHeaderView.ResizeMode.ResizeToContents)
