from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from .forms import RegisterForm
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib import messages
from django.contrib.auth import logout
from library.models import QivipQuiz, QivipQuestion


# Create your views here.
@login_required
def home(request):
    my_quizzes_number=QivipQuiz.objects.filter(user_id=request.user).count()
    my_questions_number = QivipQuestion.objects.filter(quiz_id__user_id=request.user).count()
    context = {
        'my_quizzes_number': my_quizzes_number,
        'my_questions_number': my_questions_number,
    }
    return render(request, 'accounts/home.html', context=context)



def register(response):
    if response.method == "POST":
        form = RegisterForm(response.POST)
        if form.is_valid():
            user=form.save()
            login(response, user) #automatischer Login nach Registrierung 
            return redirect("accounts:home")
    else:
        form = RegisterForm()

    return render(response, "accounts/register.html", {"form":form})

from django.contrib.auth import views as auth_views

@login_required
def password_changed(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            user = form.save()
            #update_session_auth_hash(request, user) #Hier wäre der User nach Passwortänderung noch angemeldet!
            logout(request)
            messages.success(request, "Das Passwort wurde erfolgreich geändert!")
            return redirect('accounts:home')
            
    else:
        form = PasswordChangeForm(user=request.user)
    
    return render(request, 'registration/password_change_form.html', {'form': form})


@login_required
def deleteAccount(request):
    if request.method == 'POST':
        user=request.user
        logout(request)
        user.delete()
        messages.success(request, "Der Account wurde erfolgreich gelöscht!")
        return redirect('homepage:home')
    return render(request, 'registration/delete_account_confirm.html')

