import sys

from importlib import import_module
from six import reraise

from distribution import app
from .base import Model, ValidationError

MODELS_MAP = app.config['MODELS_MAP']


def import_model(dotted_path):
    """
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImportError if the import failed.
    Taken from https://github.com/django/django/blob/1.11b1/django/utils/module_loading.py#L9
    """
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        exc_type, exc_value, tb = sys.exc_info()
        msg = "%s doesn't look like a module path" % dotted_path
        reraise(ImportError, ImportError(msg), tb)

    module = import_module(module_path)

    try:
        return getattr(module, class_name)
    except AttributeError:
        exc_type, exc_value, tb = sys.exc_info()
        msg = 'Module "%s" does not define a "%s" attribute/class' % (
            module_path, class_name)
        reraise(ImportError, ImportError(msg), tb)


def get_model(modelname):
    return import_model(MODELS_MAP[modelname])


__all__ = [
    get_model,
    Model,
    ValidationError
]
