import collections
import inspect

from django.utils.module_loading import import_string
from django.utils.text import camel_case_to_spaces
from django.utils.translation import gettext


class MappingActionRegistry:
    """
    Simple registry class for registering available actions for mapping classes.
    """

    def __init__(self):
        self._actions = collections.defaultdict(
            lambda: [
                (None, "---"),
                ("odin.mapping.helpers.sum_fields", gettext("Sum")),
                ("ocyan.plugin.oscar_odin.actions.combine", gettext("Combine")),
                (
                    "ocyan.plugin.oscar_odin.actions.commasplit",
                    gettext("Split by commas"),
                ),
                (
                    "ocyan.plugin.oscar_odin.actions.spacesplit",
                    gettext("Split by spaces"),
                ),
            ]
        )

    def register(self, cls, action_module_string, display_name=None):
        function = import_string(action_module_string)
        if display_name is None:
            display_name = inspect.getdoc(function)
        if display_name is None:
            display_name = (
                camel_case_to_spaces(function.__name__).split("_").capitalize()
            )

        self._actions[cls] += (action_module_string, display_name)

    def get(self, cls):
        return self._actions[cls]

    @property
    def actions(self):
        return self._actions


mapping_action_registry = MappingActionRegistry()
