import os

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

from openlog.datamodel.connection.interfaces.write_interface import WriteInterface
from openlog.datamodel.connection.openlog_connection import OpenLogConnection
from openlog.toolbelt import PlgTranslator


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

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

        self._openlog_connection = openlog_connection

        # translation
        self.tr = PlgTranslator().tr
        self.setWindowTitle(self.tr("Collar creation"))

        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 remove_temp_layer(self) -> None:
        """
        Remove temporary layer used by CollarCreationWidget

        Must be called when widget is not used anymore

        """
        self.collar_creation_widget.remove_temp_layer()

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

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

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

        """
        valid = True
        try:
            self.person_selection_widget.import_data()
            self.dataset_selection_widget.import_data()
            collars = self.collar_creation_widget.get_collar_list()
            # Define collar dataset and loaded_by person from current widget
            for collar in collars:
                collar.loaded_by = self.person_selection_widget.selected_person_code()
                collar.data_set = self.dataset_selection_widget.selected_dataset()
            self._openlog_connection.get_write_iface().import_collar(collars)
            self._openlog_connection.commit()
        except WriteInterface.ImportException as exc:
            valid = False
            QMessageBox.warning(self, self.tr("Import exception"), str(exc))
        if valid:
            super(CollarCreationDialog, self).accept()
