from openlog.plugins.connections.bdgeo.bdgeo_connection import BDGeoConnection
from openlog.plugins.connections.bdgeo.bdgeo_connection_dialog import (
    BDGeoConnectionDialog,
)
from openlog.plugins.hookspecs import ConnectionHook, hookimpl

#: Name of the plugin that will be referenced in our configuration
PLUGIN_NAME = "BD Geo"

# PyQGIS
from qgis.core import QgsApplication
from qgis.PyQt.QtWidgets import QAction


def bdgeo_action(openlog) -> QAction:
    """
    Function called from plugin manager.
    Args:
        - parent : mainWindow
        - openlog : OpenlogPlugin instance
    """

    def bdgeo_connect() -> None:
        """
        Execute ConnectionDialog for xplordb database connection

        """
        widget = BDGeoConnectionDialog(openlog.iface.mainWindow())
        if widget.exec():
            connection = widget.get_connection_model()
            openlog._define_current_connection(BDGeoConnection(connection))

    bdgeo_connect_action = QAction(
        QgsApplication.getThemeIcon("mIconPostgis.svg"),
        PLUGIN_NAME,
        openlog.iface.mainWindow(),
    )
    bdgeo_connect_action.triggered.connect(bdgeo_connect)

    return bdgeo_connect_action


@hookimpl
def connection():
    return ConnectionHook(
        name=PLUGIN_NAME,
        connection_action=bdgeo_action,
        connection_class=BDGeoConnection,
    )
