import urllib.parse

from django.conf import settings
from django.contrib.auth import views as auth_views
from django.http import HttpResponseRedirect
from django.shortcuts import resolve_url


if 'mellon' in settings.INSTALLED_APPS:
    from mellon.utils import get_idps
else:

    def get_idps():
        return []


def login(request, *args, **kwargs):
    if any(get_idps()):
        if 'next' not in request.GET:
            return HttpResponseRedirect(resolve_url('mellon_login'))
        return HttpResponseRedirect(
            resolve_url('mellon_login') + '?next=' + urllib.parse.quote(request.GET.get('next'))
        )
    return auth_views.LoginView.as_view(*args, **kwargs)(request)


def logout(request, *args, **kwargs):
    if any(get_idps()):
        return HttpResponseRedirect(resolve_url('mellon_logout'))
    return auth_views.LogoutView.as_view(*args, **kwargs)(request)
