from oslandia.gui.helpdesk.mdl_project import ProjectListModel
from oslandia.helpdesk.check_connection import check_connection_for_current_settings


class ProjectListModelManager:
    """Class to be use as a singleton. Mutualize ProjectListModel creation for a group.

    Example:

    .. code-block:: python

        self.mdl_project = ProjectListModelManager.get_model_for_group(5)
    """

    # Store project list model for a group
    _group_model_dict: dict[str, ProjectListModel] = {}

    @classmethod
    def init_model_for_group(cls, group_id: int) -> None:
        """Init model for a group, ProjectListModel is created and group filter defined

        :param group_id: group for filter
        :type group_id: int
        """
        if not check_connection_for_current_settings():
            return
        if not cls.has_group(group_id):
            model = ProjectListModel()
            model.set_filter(group_id)
            cls._group_model_dict[group_id] = model

    @classmethod
    def get_model_for_group(cls, group_id: int) -> ProjectListModel:
        """Get model for a group, ProjectListModel is created if needed and group filter defined

        :param group_id: group for filter
        :type group_id: int
        :return: project model list
        :rtype: ProjectListModel
        """
        if not cls.has_group(group_id):
            cls.init_model_for_group(group_id)
        return cls._group_model_dict[group_id]

    @classmethod
    def has_group(cls, group_id: int) -> bool:
        """Return true if a group is available, False otherwise

        :param group_id: group for filter
        :type group_id: int
        :return: true if a group is available, False otherwise
        :rtype: bool
        """
        return group_id in cls._group_model_dict

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