from django.shortcuts import render, resolve_url
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import views as auth_views
from mellon.utils import get_idps

import urllib

@csrf_exempt
def index(request):
    return render(request, 'index.html', locals())

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

def logout(request, next_page=None):
    if any(get_idps()):
        return HttpResponseRedirect(resolve_url('mellon_logout'))
    auth_logout(request)
    next_page = '/login' # TODO IdP-initiated SLO
    return HttpResponseRedirect(next_page)
