import os

from qgis.PyQt import QtCore, uic
from qgis.PyQt.QtWidgets import QAbstractItemView, QWidget

from openlog.gui.assay_visualization.stacked.stacked_config import StackedConfiguration
from openlog.gui.assay_visualization.stacked.stacked_config_table_model import (
    StackConfigTableModel,
)
from openlog.gui.assay_visualization.stacked.stacked_utils import invalid_series_type


class StackedConfigCreationWidget(QWidget):
    add_stacked_config = QtCore.pyqtSignal()

    def __init__(self, parent=None) -> None:
        """
        QWidget to display stacked configuration creation.

        Use StackConfigTableModel for table definition

        Args:
            parent: QWidget parent
        """
        super().__init__(parent)

        uic.loadUi(
            os.path.dirname(os.path.realpath(__file__))
            + "/stacked_config_creation_widget.ui",
            self,
        )

        self.stacked_config_table_model = StackConfigTableModel(self)
        self.tableView.setModel(self.stacked_config_table_model)
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # Check configuration for creation button enable
        self.create_push_button.setEnabled(False)
        self.stacked_config_table_model.dataChanged.connect(self._check_stacked_config)
        self.create_push_button.clicked.connect(lambda: self.add_stacked_config.emit())

    def set_stacked_configuration(self, config: StackedConfiguration) -> None:
        """
        Define displayed StackedConfiguration

        Args:
            config: StackedConfiguration
        """
        self.stacked_config_table_model.set_stacked_config(config)

    def get_stacked_configuration(self) -> StackedConfiguration:
        """
        Returns display StackedConfiguration

        Returns: StackedConfiguration

        """
        return self.stacked_config_table_model.get_stacked_config()

    def _check_stacked_config(self) -> None:
        """
        Check if StackedConfiguration is valid and enable/disable create button

        """
        stacked_config = self.get_stacked_configuration()
        self.create_push_button.setEnabled(stacked_config.is_valid())
        if not stacked_config.is_valid():
            invalid_series_name = ",".join([s.name for s in invalid_series_type()])
            self.create_push_button.setToolTip(
                self.tr(
                    f"Invalid stacked. Check if multiple unit or series type are "
                    f"used. ({invalid_series_name}) series types are not "
                    f"supported."
                )
            )
        else:
            self.create_push_button.setToolTip("")
