import traceback

from lib.db import log  # Presumendo che esista un modulo per accedere alla tabella "log"
from PyQt5.QtWidgets import QMessageBox, QTableWidget
from ui.crud import Crud, Line_Edit_Cell_Widget
from ui.widget import Widget


class Logs_Management(Widget):
    def __init__(self):
        super().__init__()

        class Info_Line_Edit_Cell_Widget(Line_Edit_Cell_Widget):
            def render(self, data, row_number=None, crud=None):
                super().render(data, row_number=row_number, crud=crud)

            def parse(self, action=None, row_number=None, crud=None):
                return self.text()

        crud_aliases = {
            "time": "Data",
            "info_type": "Operazione",
            "info": "Info",
        }
        self.crud = Crud(
            "log",
            display_name="LOG MANAGEMENT",
            readonly=["id"],
            select=list(crud_aliases.keys()),
            fields_aliases=crud_aliases,
            autocomplete={},
            widget_classes={
                "time": Info_Line_Edit_Cell_Widget,
                "info_type": Info_Line_Edit_Cell_Widget,
                "info": Info_Line_Edit_Cell_Widget,
            },
            row_filter=self.row_filter
        )

        self.layout().addWidget(self.crud, 0, 0, -1, -1)

        # Adjust the column widths based on content
        self.adjust_column_widths()

    def adjust_column_widths(self):
        """Adjust the widths of columns to fit their content."""
        # Ensure that Crud has db_tw which is a QTableWidget
        if hasattr(self.crud, 'db_tw') and isinstance(self.crud.db_tw, QTableWidget):
            # Optionally, resize all columns to fit their contents initially
            self.crud.db_tw.resizeColumnsToContents()

            # Set a specific column width for columns; for example, set 'Info' column
            for column in range(self.crud.db_tw.columnCount()):
                self.crud.db_tw.setColumnWidth(column, 175)  # Set width to 300 pixels

    def row_filter(self, row, row_number, crud):
        try:


            log_entry = log.generate(
                id=row["id"],
                time=row["time"],
                info_type=row["info_type"],
                info=row["info"]
            )
        except AssertionError as e:
            self.log.exception(traceback.format_exc())
            self.crud.set_row_color(row_number, "red")
            QMessageBox.critical(None, "Errore Salvataggio DB", f"Errore alla riga {row_number}:\n{str(e)}")
            return False, None, True

        row.update(log_entry)
        return True, row, False
