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

from openlog.datamodel.connection.openlog_connection import OpenLogConnection
from openlog.gui.utils.person_selection_widget import PersonSelectionWidget
from openlog.toolbelt.translator import PlgTranslator


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

        User can also add a person.

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

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

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

        self.person_selection = PersonSelectionWidget()
        self.person_selection.set_openlog_connection(openlog_connection)
        layout.addWidget(self.person_selection, 1, 1)
        self.person_cb = self.person_selection.get_person_combobox()
        self.setLayout(layout)

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

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

        Returns: imported data label

        """
        return self.tr("Persons")

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

        Returns: expected imported data count

        """
        return len(self.person_selection.added_persons)

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

        OpenLogConnection.ImportData exception can be raised.

        """
        self.person_selection.import_data()

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

        Returns: True if a person is selected, False otherwise

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