# 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.shortcuts import render
from django.utils.translation import gettext_noop

from authentic2.authenticators import BaseAuthenticator
from authentic2.utils.misc import make_url, redirect_to_login

from . import app_settings, utils
from .models import OIDCProvider


class OIDCAuthenticator(BaseAuthenticator):
    id = 'oidc'
    priority = 2

    def enabled(self):
        return app_settings.ENABLE and utils.has_providers()

    def name(self):
        return gettext_noop('OpenIDConnect')

    def instances(self, request, *args, **kwargs):
        for p in utils.get_providers(shown=True):
            yield (p.slug, p)

    def autorun(self, request, block_id):
        auth_id, instance_slug = block_id.split('_')
        assert auth_id == self.id

        try:
            provider = OIDCProvider.objects.get(slug=instance_slug)
        except OIDCProvider.DoesNotExist():
            return redirect_to_login(request)
        return redirect_to_login(request, login_url='oidc-login', kwargs={'pk': provider.pk})

    def login(self, request, *args, **kwargs):
        context = kwargs.get('context', {})
        if kwargs.get('instance'):
            instance = kwargs['instance']
            context['provider'] = instance
            context['login_url'] = make_url(
                'oidc-login', kwargs={'pk': instance.id}, request=request, keep_params=True
            )
            template_names = [
                'authentic2_auth_oidc/login_%s.html' % instance.slug,
                'authentic2_auth_oidc/login.html',
            ]
            return render(request, template_names, context)
