import os.path

from django.shortcuts import get_object_or_404
from django.contrib.auth import SESSION_KEY
from django import http
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required

import models
from models.user import PolynumProfile

from ..request import views as request_views

def su(request, username, redirect_url='/'):
    if request.user.is_superuser or request.session.get('has_superuser_power'):
        su_user = get_object_or_404(User, username=username)
        if su_user.is_active:
            request.session[SESSION_KEY] = su_user.id
            request.session['has_superuser_power'] = True
            return http.HttpResponseRedirect(redirect_url)
    else:
        return http.HttpResponseRedirect('/')

@login_required
def cgu(request):
    if request.method == 'POST':
        if 'ok' in request.POST:
            profile, created = PolynumProfile.objects.get_or_create(user=request.user)
            profile.accepted_cgu = True
            profile.save()
            return redirect(request.GET.get('next'))
        elif 'nok' in request.POST:
            return redirect('homepage')
    return render(request, 'cgu-form.html')

def public_document(request, pk, name=None):
    poly_request = get_object_or_404(models.Request, pk=pk)
    if not poly_request.licence or \
            'public-url' not in poly_request.licence.diffusion_tags or \
            not poly_request.uploadfile.name:
        raise http.Http404()
    if not name:
        return redirect('public-document-with-name', pk=pk,
                name=os.path.basename(poly_request.uploadfile.name))
    return request_views.request_download(request, pk)
