
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.core.context_processors import csrf
import django.contrib.auth.decorators as decorators
import django.contrib.auth as auth
import django.contrib.auth.forms as auth_forms
import django.contrib.auth.models as auth_models
import json


@decorators.login_required
def logout(request):
    if request.user.is_authenticated():
        auth.logout(request)
    return redirect('/')


def reset_password(request):
    return render(request, 'logsys/reset-password.html', {})


def login(request):
    args = {}
    args.update(csrf(request))
    if request.POST:
        auth_form = auth_forms.AuthenticationForm(request, data=request.POST)
        if auth_form.is_valid():
            auth_form.clean()
            auth.login(request, auth_form.get_user())
            return redirect('/')
        else:
            args['auth_error_p'] = True
            if request.POST['username']:
                args['tricker_id_prev_try'] = request.POST['username']
    return render(request, 'logsys/login.html', args)


def register(request):
    args = {}
    args.update(csrf(request))
    if request.POST:
        new_user_form = auth_forms.UserCreationForm(request.POST)
        if new_user_form.is_valid():
            new_user = new_user_form.save(commit=False)
            new_user.email = request.POST['email']
            new_user.first_name = request.POST.get('first-name', '')
            new_user.last_name = request.POST.get('last-name', '')
            new_user.save()
            auth.login(
                request,
                auth.authenticate(
                    username=new_user_form.cleaned_data['username'],
                    password=new_user_form.cleaned_data['password1']
                )
            )
            return redirect('/')
        else:
            pass
            # TODO reject incorrect registration
    return render(request, 'logsys/register.html', args)


def is_username_already_engaged(request, username):
    response = {'engaged': False}
    if auth_models.User.objects.filter(username=username):
        response['engaged'] = True
    return HttpResponse(json.dumps(response))


def is_email_already_engaged(request, email):
    response = {'engaged': False}
    if auth.models.User.objects.filter(email=email):
        response['engaged'] = True
    return HttpResponse(json.dumps(response))
