from enum import Enum

from PyQt5.QtWidgets import QWidget, QGridLayout, QLabel, QLineEdit, QComboBox

from openlog.datamodel.assay.generic_assay import AssayDefinition, AssayDomainType, AssaySeriesType, AssayDataExtent


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(self.tr("Variable")), 0, 0)
        self.variable_edit = QLineEdit()
        self.layout.addWidget(self.variable_edit, 0, 1)

        self.domain_cb = self._add_combobox(self.tr("Domain"), AssayDomainType)
        self.data_extent_cb = self._add_combobox(self.tr("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.variable)
        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=self.variable_edit.text(),
                               domain=AssayDomainType(self.domain_cb.currentText()),
                               data_extent=AssayDataExtent(self.data_extent_cb.currentText()),
                               columns={})

    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)
