from typing import Optional

from qgis.PyQt.QtWidgets import QWidget

from openlog.datamodel.connection.bdgeo.bdgeo_connection import BDGeoConnection
from openlog.datamodel.connection.geotic.geotic_connection import GeoticConnection
from openlog.datamodel.connection.openlog_connection import OpenLogConnection
from openlog.datamodel.connection.spatialite.spatialite_connection import (
    SpatialiteConnection,
)
from openlog.datamodel.connection.xplordb.xplordb_connection import XplordbConnection
from openlog.toolbelt import PlgLogger, PlgTranslator


class OpenLogConnectionFactory:
    def __init__(self):
        """
        Factory for OpenLogConnection creation

        """
        self.log = PlgLogger().log
        self.tr = PlgTranslator().tr

    @staticmethod
    def get_available_connections() -> dict:
        """
        Get available OpenLogConnection

        Returns: dict[str, OpenLogConnection] key is class name

        """
        return {
            BDGeoConnection.__name__: BDGeoConnection,
            GeoticConnection.__name__: GeoticConnection,
            SpatialiteConnection.__name__: SpatialiteConnection,
            XplordbConnection.__name__: XplordbConnection,
        }

    def create_connection_from_project(
        self, connection_type: str, base_settings_key: str, parent: QWidget
    ) -> Optional[OpenLogConnection]:
        """
        Create OpenLogConnection from QGIS project base settings

        Args:
            connection_type: (str) connection type saved in QGIS project
            base_settings_key: (str) base settings key
            parent: (QWidget) parent widget to use for any dialog display

        Returns: OpenLogConnection from QGIS project or None if no connection or invalid params

        """
        available_connection = self.get_available_connections()
        if connection_type in available_connection:
            connection = available_connection[connection_type].create_from_qgis_project(
                base_settings_key, parent
            )
            return connection
        else:
            self.log(
                message=self.tr(
                    f"OpenLog connection type '{connection_type}' not available. "
                    f"No connection loaded from QGIS project."
                ),
                push=True,
            )
            return None
