from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm

from .forms import RegisterForm

# Views dealing with users below

def userLogin(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('dashboard:dashboard')
        else:
            messages.info(request, 'invalid credentials')
            return redirect("users:login")
    else:
        form = AuthenticationForm()
    return render(request, 'login.html', {'form':form})


def userLogout(request):
    logout(request)
    return redirect('index')


def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('dashboard:dashboard')
        else:
            messages.info(request, 'Error')
            return redirect("users:register")
    else:
        form = RegisterForm()
    return render(request, 'register.html', {'form': form})

