from typing import Optional

from qgis.PyQt.QtWidgets import QWidget

from openlog.datamodel.connection.openlog_connection import OpenLogConnection
from openlog.plugins.manager import get_plugin_manager
from openlog.toolbelt import PlgLogger


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

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

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

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

        """

        return {
            conn_hook.connection_class.__name__: conn_hook.connection_class
            for conn_hook in get_plugin_manager().get_connections()
        }

    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=f"OpenLog connection type '{connection_type}' not available. ",
                push=True,
            )
            return None
