# authentic2 - versatile identity manager
# Copyright (C) 2010-2019 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.conf import settings
from pkg_resources import get_distribution

from . import app_settings, constants
from .models import Service
from .utils import misc as utils_misc


class UserFederations:
    '''Provide access to all federations of the current user'''

    def __init__(self, request):
        self.request = request

    def __getattr__(self, name):
        d = {'provider': None, 'links': []}
        if name.startswith('service_'):
            try:
                provider_id = int(name.split('_', 1)[1])
            except ValueError:
                pass
            else:
                links = utils_misc.accumulate_from_backends(self.request, 'links')
                for provider, link in links:
                    if provider.id != provider_id:
                        continue
                    d['provider'] = provider
                    d['links'].append(link)
            return d
        return super().__getattr__(name)


__AUTHENTIC2_DISTRIBUTION = None


def a2_processor(request):
    global __AUTHENTIC2_DISTRIBUTION
    variables = {}
    variables.update(app_settings.TEMPLATE_VARS)
    variables['federations'] = UserFederations(request)
    if __AUTHENTIC2_DISTRIBUTION is None:
        if settings.DEBUG:
            __AUTHENTIC2_DISTRIBUTION = repr(get_distribution('authentic2'))
        else:
            __AUTHENTIC2_DISTRIBUTION = str(get_distribution('authentic2'))
    variables['AUTHENTIC2_VERSION'] = __AUTHENTIC2_DISTRIBUTION
    if hasattr(request, 'session'):
        variables['LAST_LOGIN'] = request.session.get(constants.LAST_LOGIN_SESSION_KEY)
        variables['USER_SWITCHED'] = constants.SWITCH_USER_SESSION_KEY in request.session
        if 'service_pk' in request.session:
            try:
                variables['service'] = Service.objects.get(pk=request.session['service_pk'])
            except Service.DoesNotExist:
                pass
    return variables
