from importlib import machinery
from os import listdir
from os.path import dirname, splitext

from django.template import loaders

MODULE_EXTENSIONS = tuple(machinery.all_suffixes())


def get_django_template_loaders():
    return [
        (loader.__name__.rsplit(".", 1)[1], loader) for loader in get_submodules(loaders) if hasattr(loader, "Loader")
    ]


def get_submodules(package):
    submodules = ("%s.%s" % (package.__name__, module) for module in package_contents(package))
    return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]]) for module in submodules]


def package_contents(package):
    package_path = dirname(loaders.__file__)
    contents = set([splitext(module)[0] for module in listdir(package_path) if module.endswith(MODULE_EXTENSIONS)])
    return contents
