from openlog.datamodel.connection.xplordb.xplordb_connection import XplordbConnection
from openlog.gui.connection.xplordb_connection_dialog import XplordbConnectionDialog
from openlog.plugins.hookspecs import ConnectionHook, hookimpl

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

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


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

    def xplordb_connect():

        widget = XplordbConnectionDialog(openlog.iface.mainWindow())
        if widget.exec():
            connection = widget.get_connection_model()
            openlog._define_current_connection(XplordbConnection(connection))

            # update database if not up-to-date with xplordb schema
            if openlog.openlog_connection.updater.need_update():
                openlog.openlog_connection.updater.update_database(openlog.iface)
                openlog._unload_loaded_layer()

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

    return xplordb_connect_action


@hookimpl
def connection():
    return ConnectionHook(
        name=PLUGIN_NAME,
        connection_action=xplordb_action,
        connection_class=XplordbConnection,
    )
