from PySide6.QtWidgets import QDialog, QTableWidgetItem
from ui.ProjectXsltParamsDialog_ui import Ui_ProjectXsltParamsDialog
from icons import icon


class ProjectXsltParamsDialog(QDialog):
    """Dialog zur Bearbeitung projektweiter XSLT-Parameter."""

    def __init__(self, parent=None, xslt_params: dict[str, str] | None = None):
        super().__init__(parent)

        self.ui = Ui_ProjectXsltParamsDialog()
        self.ui.setupUi(self)

        self.ui.addParamButton.setIcon(icon("plus-circle"))
        self.ui.removeParamButton.setIcon(icon("minus-circle"))

        self.ui.addParamButton.clicked.connect(self._add_parameter)
        self.ui.removeParamButton.clicked.connect(self._remove_parameter)

        self._setup_table()

        if xslt_params:
            self._load_params(xslt_params)

    def _setup_table(self):
        """Konfiguriert die Tabelle."""
        self.ui.xsltParamsTable.setColumnWidth(0, 200)
        self.ui.xsltParamsTable.setColumnWidth(1, 300)
        self.ui.xsltParamsTable.horizontalHeader().setStretchLastSection(True)

    def _load_params(self, params: dict[str, str]):
        """Lädt die XSLT-Parameter in die Tabelle."""
        self.ui.xsltParamsTable.setRowCount(len(params))
        for row, (key, value) in enumerate(params.items()):
            self.ui.xsltParamsTable.setItem(row, 0, QTableWidgetItem(str(key)))
            self.ui.xsltParamsTable.setItem(row, 1, QTableWidgetItem(str(value)))

    def _add_parameter(self):
        """Fügt einen neuen Parameter hinzu."""
        row_count = self.ui.xsltParamsTable.rowCount()
        self.ui.xsltParamsTable.insertRow(row_count)
        self.ui.xsltParamsTable.setItem(row_count, 0, QTableWidgetItem(""))
        self.ui.xsltParamsTable.setItem(row_count, 1, QTableWidgetItem(""))
        self.ui.xsltParamsTable.setCurrentCell(row_count, 0)

    def _remove_parameter(self):
        """Entfernt den ausgewählten Parameter."""
        current_row = self.ui.xsltParamsTable.currentRow()
        if current_row >= 0:
            self.ui.xsltParamsTable.removeRow(current_row)

    def get_params(self) -> dict[str, str]:
        """
        Gibt die bearbeiteten XSLT-Parameter zurück.

        Returns:
            dict[str, str]: Dictionary mit allen XSLT-Parametern
        """
        params = {}
        for row in range(self.ui.xsltParamsTable.rowCount()):
            key_item = self.ui.xsltParamsTable.item(row, 0)
            value_item = self.ui.xsltParamsTable.item(row, 1)
            if key_item and value_item:
                key = key_item.text().strip()
                if key:
                    params[key] = value_item.text().strip()
        return params
