# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.apps import apps
from django.conf.urls import patterns, include, url

from .urls_utils import decorated_includes, required, app_enabled, manager_required


def register_apps_urls(urlpatterns):
    '''Call get_before_urls and get_after_urls on all apps providing them,
       add those urls to the given urlpatterns (before or after).
    '''
    before_urls = []
    after_urls = []
    for app in apps.get_app_configs():
        if hasattr(app, 'get_before_urls') or hasattr(app, 'get_after_urls'):
            if hasattr(app, 'get_before_urls'):
                urls = app.get_before_urls()
                if urls:
                    before_urls.append(url('^', include(urls)))
            if hasattr(app, 'get_after_urls'):
                urls = app.get_after_urls()
                if urls:
                    after_urls.append(url('^', include(urls)))
        elif hasattr(app, 'get_urls'):
            url_prefix = '^%s/' % app.get_connector_model().get_connector_slug()
            urls = app.get_urls()
            if urls:
                urls = required(app_enabled(app.label), urls)
                after_urls.append(url(url_prefix, include(urls)))
        if hasattr(app, 'get_management_urls'):
            url_prefix = '^manage/%s/' % app.get_connector_model().get_connector_slug()
            urls = app.get_management_urls()
            if urls:
                urls = required(app_enabled(app.label), urls)
                urls = required(manager_required, urls)
                after_urls.append(url(url_prefix, include(urls)))

    before_patterns = patterns('', *before_urls)
    after_patterns = patterns('', *after_urls)
    return before_patterns + urlpatterns + after_patterns
