# 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.template.loader import render_to_string
from django.utils.translation import gettext_noop
from mellon.utils import get_idp, get_idps

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

from . import app_settings


class SAMLAuthenticator(BaseAuthenticator):
    id = 'saml'
    priority = 3

    def enabled(self):
        return app_settings.enable and list(get_idps())

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

    def instances(self, request, *args, **kwargs):
        for idx, idp in enumerate(get_idps()):
            yield (idp.get('SLUG') or str(idx), idp)

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

        for slug, instance in self.instances(request):
            if slug == instance_slug:
                return redirect_to_login(
                    request, login_url='mellon_login', params={'entityID': instance['ENTITY_ID']}
                )
        return redirect_to_login(request)

    def login(self, request, *args, **kwargs):
        context = kwargs.pop('context', {})
        instance_id = kwargs.get('instance_id')
        submit_name = 'login-%s-%s' % (self.id, instance_id)
        context['submit_name'] = submit_name
        if request.method == 'POST' and submit_name in request.POST:
            instance = kwargs.get('instance')
            return redirect_to_login(
                request, login_url='mellon_login', params={'entityID': instance['ENTITY_ID']}
            )
        return render(
            request,
            ['authentic2_auth_saml/login_%s.html' % instance_id, 'authentic2_auth_saml/login.html'],
            context,
        )

    def profile(self, request, *args, **kwargs):
        context = kwargs.pop('context', {})
        user_saml_identifiers = request.user.saml_identifiers.all()
        if not user_saml_identifiers:
            return ''
        for user_saml_identifier in user_saml_identifiers:
            user_saml_identifier.idp = get_idp(user_saml_identifier.issuer)
        context['user_saml_identifiers'] = user_saml_identifiers
        return render_to_string('authentic2_auth_saml/profile.html', context, request=request)
