from qgis.PyQt.QtWidgets import QGridLayout, QLabel, QSizePolicy, QWidget, QWizardPage

from openlog.datamodel.connection.openlog_connection import OpenLogConnection
from openlog.gui.utils.dataset_selection_widget import DatasetSelectionWidget
from openlog.toolbelt.translator import PlgTranslator


class DatasetSelectionPageWizard(QWizardPage):
    def __init__(self, parent: QWidget, openlog_connection: OpenLogConnection) -> None:
        """
        QWizard to select dataset for xplordb import.

        User can also add a dataset.

        Args
            openlog_connection: OpenLogConnection used to import dataset
            parent : QWidget parent
        """
        super().__init__(parent)
        self.tr = PlgTranslator().tr
        self._openlog_connection = openlog_connection
        self.setTitle(self.tr("Dataset definition"))

        label = QLabel(self.tr("Select a dataset for import."))
        label.setWordWrap(True)

        layout = QGridLayout()
        layout.addWidget(label, 0, 0, 1, 2)
        dataset_label = QLabel(self.tr("Dataset"))
        dataset_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        layout.addWidget(dataset_label, 1, 0)

        self.dataset_selection = DatasetSelectionWidget()
        self.dataset_selection.set_openlog_connection(openlog_connection)
        layout.addWidget(self.dataset_selection, 1, 1)
        self.dataset_cb = self.dataset_selection.get_dataset_combobox()
        self.setLayout(layout)

        # Register dataset combobox and use text instead of index
        self.registerField(
            "dataset",
            self.dataset_cb,
            "currentText",
            self.dataset_cb.currentTextChanged,
        )

    def data_label(self) -> str:
        """
        Returns label to be used in confirmation dialog

        Returns: imported data label

        """
        return self.tr("Datasets")

    def data_count(self) -> int:
        """
        Returns expected imported data count to be displayed in confirmation dialog

        Returns: expected imported data count

        """
        return len(self.dataset_selection.added_datasets)

    def import_data(self):
        """
        Import data into openlog database.

        OpenLogConnection.ImportData exception can be raised.

        """
        self.dataset_selection.import_data()

    def initializePage(self) -> None:
        """
        Define used person for dataset creation and refresh available dataset

        """
        self.dataset_selection.set_loaded_by_person(self.field("person"))

    def validatePage(self) -> bool:
        """
        Validate page by checking that a dataset is selected

        Returns: True if a dataset is selected, False otherwise

        """
        return len(self.dataset_cb.currentText()) != 0
