# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2016 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/>.

import django.apps
from django.apps import apps
from django.utils.module_loading import import_string


class ConnectorAppMixin:
    def get_connector_model(self):
        return self._connector_model

    def get_urls(self):
        try:
            return import_string('%s.urls.urlpatterns' % self.name)
        except ImportError:
            return None

    def get_management_urls(self):
        try:
            return import_string('%s.urls.management_urlpatterns' % self.name)
        except ImportError:
            return None


class ConnectorAppConfig(ConnectorAppMixin, django.apps.AppConfig):
    pass


class AppConfig(django.apps.AppConfig):
    name = 'passerelle.base'

    def ready(self):
        # once all applications are ready, go through them and mark them as
        # connectors if they have a get_connector_model() method or a model
        # that inherits from BaseResource.
        from .models import BaseResource

        for app in apps.get_app_configs():
            connector_model = None
            if hasattr(app, 'get_connector_model'):
                connector_model = app.get_connector_model()
            else:
                for model in app.get_models():
                    if issubclass(model, BaseResource):
                        connector_model = model
                        app._connector_model = model
                        break
            if not connector_model:
                continue
            if app.__class__ is django.apps.AppConfig:
                # switch class if it's an application without a custom
                # appconfig.
                app.__class__ = ConnectorAppConfig
            else:
                # add mixin to base classes if it's an application with a
                # custom appconfig.
                app.__class__.__bases__ = (ConnectorAppMixin,) + app.__class__.__bases__


default_app_config = 'passerelle.base.AppConfig'
