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

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, get_user
from django.contrib.auth.models import User
from django.http import Http404
from django.http import JsonResponse
from home.forms import *

def homepage(request):
    """
    Render home page.
    """
    return render(request, 'home/homepage.html', locals())

def contact(request):
    """
    Form validation and contact page rendering.
    """
    user = get_user(request)
    form = ContactForm(request.POST or None, initial={'email': user.email if user.is_authenticated else ''})
    if request.method == "POST":
        if form.is_valid():
            #TODO send email ? save into database ?
            data = {
                'sent':True
            }
            if('HTTP_X_REQUESTED_WITH' in request.META and request.META['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'):
                return JsonResponse(data)
            return render(request, 'home/contact.html', locals())
        else:
            #hack attempt, log it
            print(request.POST)
    elif request.method == "GET":
        return render(request, 'home/contact.html', locals())
    raise Http404

def article(request):
    return render(request, 'home/article.html')