from django.shortcuts import render, redirect
from django.http import HttpResponse

from django.contrib import messages
from django.contrib.auth import authenticate, logout
from django.contrib.auth import login as auth_login
from django.contrib.auth.models import User

def lor(request):
    return render(request, 'lor.html')

def login(request):
    if request.method == 'POST':
        username  = request.POST['username']
        password  = request.POST['password']

        user = authenticate(username=username, password=password)
        if user is not None:
            # the password verified for the user
            if user.is_active:
                auth_login(request, user)
                return redirect('dashboard')
            else:
                messages.error(request, 'This account has been disabled.')
                return redirect('lor')
        else:
            # the authentication system was unable to verify the username and password
            messages.error(request, 'Invalid username or password.')
            return redirect('lor')

def register(request):
    if request.method == 'POST':
        username  = request.POST['username']
        password  = request.POST['password']
        email     = request.POST['email']
        api_token = request.POST['api_token']

        user = User.objects.create_user(username, email, password)
        user.api_token = api_token

        user.save()
        messages.success(request, 'Account successfully created!')
        return redirect('lor')

def logout_user(request):
    logout(request)
    messages.success(request, 'Successfully logged out.')
    return redirect('index')
