from oslandia.gitlab_api.check_connection import check_connection_for_current_settings
from oslandia.gui.mdl_members import MembersListModel


class MemberListModelManager:
    """Class to be use as a singleton. Mutualize MembersListModel creation for a project.

    Example:

    .. code-block:: python

        self.mdl_members = MemberListModelManager.get_model_for_project(project_id)
    """

    # Store project list model for a project
    _project_model_dict: dict[int, MembersListModel] = {}

    @classmethod
    def init_model_for_project(cls, project_id: int) -> None:
        """Init model for a project, MembersListModel is created and project filter defined

        :param project_id: project for filter
        :type project_id: int
        """
        if not check_connection_for_current_settings():
            return
        if not cls.has_project(project_id):
            model = MembersListModel()
            model.set_filter(project_id)
            cls._project_model_dict[project_id] = model

    @classmethod
    def get_model_for_project(cls, project_id: int) -> MembersListModel:
        """Get model for a project, MembersListModel is created if needed and project filter defined

        :param project_id: project for filter
        :type project_id: int
        :return: project model list
        :rtype: MembersListModel
        """
        if not cls.has_project(project_id):
            cls.init_model_for_project(project_id)
        return cls._project_model_dict[project_id]

    @classmethod
    def has_project(cls, project_id: int) -> bool:
        """Return true if a project is available, False otherwise

        :param project_id: project for filter
        :type project_id: int
        :return: true if a project is available, False otherwise
        :rtype: bool
        """
        return project_id in cls._project_model_dict

    @classmethod
    def clear(cls) -> None:
        """Clear project model dict"""
        cls._project_model_dict.clear()
