from django.conf.urls import patterns, include, url
from django.contrib import admin
from mainstay.settings import MAINSTAY_APPS, DEBUG
import importlib


def get_found_patterns():
    found_patterns = []

    for app in MAINSTAY_APPS:
        basename = app.rsplit('.')[-1]
        try:
            url_mod = importlib.import_module(app + '.urls')
        except ImportError as e:
            # there is no urls module
            if DEBUG:
                print(e)
            continue
        try:
            prefix = url_mod.PREFIX
        except AttributeError:
            prefix = basename

        try:
            namespace = url_mod.NAMESPACE
        except AttributeError:
            namespace = basename

        found_patterns.append(url(r'^' + prefix, include(app + '.urls', namespace=namespace)))
    return found_patterns

found_patterns = get_found_patterns() + [url(r'^admin/', include(admin.site.urls))]

urlpatterns = patterns(
    '',
    *found_patterns)
