from enum import Enum

from qgis.PyQt.QtWidgets import QComboBox, QGridLayout, QLabel, QLineEdit, QWidget

from openlog.datamodel.assay.generic_assay import (
    AssayDataExtent,
    AssayDefinition,
    AssayDomainType,
    AssaySeriesType,
)
from openlog.gui.import_assay.utils import sanitize_sql_name


class AssayDefinitionWidget(QWidget):
    def __init__(self, parent: QWidget = None):
        """
        QWidget to display AssayDefinition

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

        self.layout = QGridLayout()

        self.layout.addWidget(QLabel("Variable"), 0, 0)
        self.variable_edit = QLineEdit()
        self.layout.addWidget(self.variable_edit, 0, 1)

        self.domain_cb = self._add_combobox("Domain", AssayDomainType)
        self.data_extent_cb = self._add_combobox("Extent", AssayDataExtent)

        self.setLayout(self.layout)

    def set_assay_definition(self, assay_definition: AssayDefinition) -> None:
        """
        Update widget with assay definition

        Args:
            assay_definition: AssayDefinition
        """
        self.variable_edit.setText(assay_definition.display_name)
        self.domain_cb.setCurrentText(assay_definition.domain.value)
        self.data_extent_cb.setCurrentText(assay_definition.data_extent.value)

    def get_assay_definition_without_columns(self) -> AssayDefinition:
        """
        Returns current assay definition

        Returns: AssayDefinition

        """
        return AssayDefinition(
            variable=sanitize_sql_name(self.variable_edit.text()),
            domain=AssayDomainType(self.domain_cb.currentText()),
            data_extent=AssayDataExtent(self.data_extent_cb.currentText()),
            columns={},
            display_name=self.variable_edit.text(),
        )

    def _add_combobox(self, name: str, enum: Enum) -> QComboBox:
        """
        Add combobox and label to layout and returns created combobox

        Args:
            name: label for combobox
            enum: enum for combobox

        Returns: created QComboBox

        """
        row_count = self.layout.rowCount()
        self.layout.addWidget(QLabel(name), row_count, 0)
        cb = QComboBox()
        self._init_cb_from_enum(cb, enum)
        self.layout.addWidget(cb, row_count, 1)
        return cb

    @staticmethod
    def _init_cb_from_enum(cb: QComboBox, enum: Enum):
        """
        Initialize combobox from enum available values

        Args:
            cb: QComboBox
            enum: Enum
        """
        for e in enum:
            cb.addItem(e.value)
