import os

from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QDialog, QMessageBox

from openlog.datamodel.connection.openlog_connection import OpenLogConnection
from openlog.toolbelt import PlgTranslator


class SurveyCreationDialog(QDialog):
    def __init__(self, openlog_connection: OpenLogConnection, parent=None) -> None:
        """
        QDialog to create survey

        Args:
            openlog_connection: OpenLogConnection interface for data import
            parent: QWidget parent
        """
        super(SurveyCreationDialog, self).__init__(parent)
        uic.loadUi(
            os.path.join(os.path.dirname(__file__), "survey_creation_dialog.ui"), self
        )

        self._openlog_connection = openlog_connection

        # translation
        self.tr = PlgTranslator().tr
        self.setWindowTitle(self.tr("Survey creation/edition"))

        self.person_selection_widget.set_openlog_connection(self._openlog_connection)
        self.dataset_selection_widget.set_openlog_connection(self._openlog_connection)

        self.person_selection_widget.person_changed.connect(
            lambda code: self.dataset_selection_widget.set_loaded_by_person(code)
        )

        self.dataset_selection_widget.set_loaded_by_person(
            self.person_selection_widget.selected_person_code()
        )

    def set_selected_collar(self, collars: [str]):
        """
        Define selected collar for survey definition
        If only one collar is available, use current survey list as input

        Args:
            collars:
        """
        self.collars_check_combobox.addItems(collars)
        self.collars_check_combobox.setCheckedItems(collars)

        if len(collars) == 1:
            self.survey_creation_widget.add_planned_survey_button.setEnabled(False)
            self.survey_creation_widget.remove_planned_survey_button.setEnabled(False)
            surveys = (
                self._openlog_connection.get_read_iface().get_surveys_from_collars(
                    [collars[0]]
                )
            )

            planned_surveys = (
                self._openlog_connection.get_read_iface().get_surveys_from_collars(
                    [collars[0]], planned=True
                )
            )

            self.survey_creation_widget.add_surveys(surveys)
            collar = self._openlog_connection.get_read_iface().get_collar(collars[0])
            self.survey_creation_widget.add_planned_surveys(planned_surveys, collar)

    def rejected(self) -> None:
        """
        Rollback openlog connection if survey creation is rejected

        """
        self._openlog_connection.rollback()
        super(SurveyCreationDialog).rejected()

    def accept(self) -> None:
        """
        Import survey from current survey creation widget

        """
        valid = True

        surveys = self.survey_creation_widget.get_survey_list()
        planned_surveys = self.survey_creation_widget.get_planned_survey_list()

        if any(s.depth is None or s.dip is None or s.azimuth is None for s in surveys):
            ret = QMessageBox.question(
                self,
                self.tr("Null data entries"),
                self.tr(
                    "Null data entries found, press OK to discard them and proceed."
                ),
            )
            if ret == QMessageBox.Yes:
                surveys = [
                    s
                    for s in surveys
                    if s.depth is not None
                    and s.dip is not None
                    and s.azimuth is not None
                ]
            else:
                valid = False

        if valid:
            try:
                self.person_selection_widget.import_data()
                self.dataset_selection_widget.import_data()

                for hole_id in self.collars_check_combobox.checkedItems():
                    # effective surveys
                    # Define survey dataset and loaded_by person from current widget
                    for survey in surveys:
                        survey.loaded_by = (
                            self.person_selection_widget.selected_person_code()
                        )
                        survey.data_set = (
                            self.dataset_selection_widget.selected_dataset()
                        )
                        survey.hole_id = hole_id
                    self._openlog_connection.get_write_iface().replace_collar_surveys(
                        hole_id, surveys
                    )

                    # planned surveys
                    self._openlog_connection.get_write_iface().replace_collar_planned_surveys(
                        hole_id, planned_surveys[0]
                    )

                self._openlog_connection.commit()
            except OpenLogConnection.ImportException as exc:
                valid = False
                QMessageBox.warning(self, self.tr("Import exception"), str(exc))
        if valid:
            super(SurveyCreationDialog, self).accept()
