#-*- coding: utf-8 -*-

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.contrib.auth import login as a_login, logout as a_logout
from django.core.urlresolvers import reverse
from django.conf import settings as s
from django.http import JsonResponse
from django.http import Http404
from account.forms import *
from home.views import homepage

def login(request):
    """
        Login validation
        Only accessible with ajax POST from menu and return json
    """
    form = LoginForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(username=username, password=password)
            if user:
                a_login(request, user)
                data = {
                    'login':True
                }
            else:
                data = {
                    'login':False
                }
                if(User.objects.filter(username=username).exists()):
                    data['error'] = 'Mauvais mot de passe'
                else:
                    data['error'] = 'Identifiant inconnu'
            if('HTTP_X_REQUESTED_WITH' in request.META and request.META['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'):
                return JsonResponse(data)
            return render(request, 'account/login.html', locals())
        else:
            #hack attempt, log it
            print(request.POST)
    elif request.method == "GET":
        return render(request, 'account/login.html')

    raise Http404

def logout(request):
    """
        Logout user
        with ajax POST from menu and reload page
    """
    a_logout(request)
    return redirect(reverse(homepage))


def signup(request):
    """
        Signup user
        with ajax POST from signup page and return json
    """
    form = InscriptionForm()
    if request.method == "POST":
        if form.is_valid():
            password1 = form.cleaned_data["password1"]
            password2 = form.cleaned_data["password2"]
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            cgu = form.cleaned_data["cgu"]
            if(password1 != password2):
                data = {
                    'registered':False,
                    'error':"Les mots de passe ne sont pas identique !"
                }
            elif(User.objects.filter(username=username).exists()):
                data = {
                    'registered':False,
                    'error':"Ce nom d'utilisateur est déjà utilisé !"
                }
            elif(User.objects.filter(email=email).exists()):
                data = {
                    'registered':False,
                    'error':"Cette adresse email est déjà utilisé !"
                }
            else:
                create_user(username, email, password1)
                authenticate(username, password1)
                data = {
                    'registered':True
                }

            if('HTTP_X_REQUESTED_WITH' in request.META and request.META['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'): 
                return JsonResponse(data)
            return render(request, 'account/signup.html', locals())
    elif request.method == "GET":
        return render(request, 'account/signup.html', locals())
    raise Http404

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