from django.shortcuts import render, redirect
from django.contrib.auth import login, logout
from django.contrib import messages
from django.contrib.auth.models import User

from documents.etherpadlib import del_ep_cookie

from .authentications import authentication
from .decorators import unauthenticated_user, authenticated_user
from .forms import LoginForm


@unauthenticated_user
def loginPage(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        auth_user = authentication(username, password)

        if auth_user is not None:
            try:
                user = User.objects.get(username=auth_user.lower())
            except User.DoesNotExist:
                user = User.objects.create_user(auth_user.lower())

            login(request, user)

            try:
                return redirect(request.GET.get("next"))
            except:
                return redirect("home")
        else:
            messages.info(request, "username or password is incorrect")

    form = LoginForm()

    context = {
        "form": form,
    }
    return render(request, "authentications/login.html", context)


@authenticated_user
def logoutUser(request):
    logout(request)

    try:
        response = redirect(request.GET.get("next"))
    except:
        response = redirect("home")

    response = del_ep_cookie(request, response)

    return response
