#! python3  # noqa: E265

"""
    Plugin settings form integrated into QGIS 'Options' menu.
"""

# standard
from pathlib import Path

from qgis.gui import QgsDatabaseSchemaComboBox, QgsProviderConnectionComboBox

# PyQGIS
from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QDialog, QVBoxLayout

# project
from plui_versionning.toolbelt import PlgLogger, PlgOptionsManager

# ############################################################################
# ########## Globals ###############
# ##################################

# FORM_CLASS, _ = uic.loadUiType(
#     Path(__file__).parent / "{}.ui".format(Path(__file__).stem)
# )


# ############################################################################
# ########## Classes ###############
# ##################################


class DatabaseSettings(QDialog):
    """Settings form embedded into QGIS 'options' menu."""

    def __init__(self, parent):
        super().__init__(parent)
        self.log = PlgLogger().log
        self.plg_settings = PlgOptionsManager()

        uic.loadUi(Path(__file__).parent / f"{Path(__file__).stem}.ui", self)

        # Setup Database UI
        group_layout = QVBoxLayout()
        self.dbGroupBox.setLayout(group_layout)
        self.db_connection_item = QgsProviderConnectionComboBox("postgres")
        self.db_schema_source_item = QgsDatabaseSchemaComboBox(
            "postgres", self.db_connection_item.currentConnection()
        )
        group_layout.addWidget(self.db_connection_item)
        group_layout.addWidget(self.db_schema_source_item)
        self.db_connection_item.connectionChanged.connect(self.connection_changed)
        self.buttonBox.accepted.connect(self.apply)

        # load previously saved settings
        self.load_settings()

    def apply(self):
        """Called to permanently apply the settings shown in the options page (e.g. \
        save them to QgsSettings objects). This is usually called when the options \
        dialog is accepted."""
        db_connection_name = self.db_connection_item.currentConnection()
        db_connection_uri = self.db_connection_item.currentConnectionUri()
        db_schema_name = self.db_schema_source_item.currentSchema()

        plg_settings = self.plg_settings.get_plg_settings()
        plg_settings.db_connection_name = db_connection_name
        plg_settings.db_connection_uri = db_connection_uri
        plg_settings.db_schema_name = db_schema_name
        self.plg_settings.save_from_object(plg_settings)

        if __debug__:
            self.log(
                message="DEBUG - Settings successfully saved.",
                log_level=4,
            )

    def load_settings(self):
        """Load options from QgsSettings into UI form."""
        settings = self.plg_settings.get_plg_settings()

        # DB connection
        self.db_connection_item.setConnection(settings.db_connection_name)
        self.db_schema_source_item.setConnectionName(settings.db_connection_name)
        self.db_schema_source_item.setSchema(settings.db_schema_name)

    def connection_changed(self):
        """Load schemas for the selected connection."""
        self.db_schema_source_item.setConnectionName(
            self.db_connection_item.currentConnection()
        )
