from django.conf import settings
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import views as auth_views
from django.http import HttpResponseRedirect
from django.shortcuts import resolve_url
from django.utils.http import quote
from django.views.generic.base import TemplateView

from .projects.models import Project

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

    def get_idps():
        return []


class LoginView(auth_views.LoginView):
    def get(self, 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=' + quote(request.GET.get('next'))
            )
        return super().get(request, *args, **kwargs)


login = LoginView.as_view()


def logout(request, next_page=None):
    if any(get_idps()):
        return HttpResponseRedirect(resolve_url('mellon_logout'))
    auth_logout(request)
    if next_page is not None:
        next_page = resolve_url(next_page)
    else:
        next_page = '/'
    return HttpResponseRedirect(next_page)


class Home(TemplateView):
    template_name = 'scrutiny/home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['projects'] = Project.objects.all()
        return context


home = Home.as_view()
