import json

from django.conf import settings
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404


def render_to_json_response(dictionary, content_type="application/json; charset=utf-8", status=200):
    try:
        response = json.dumps(dictionary, ensure_ascii=False) + '\n'
    except TypeError:
        logger.error('failed to serialize to JSON: %s', dictionary)
        raise
    if not isinstance(response, bytes):
        response = response.encode('utf-8')
    return HttpResponse(response, content_type=content_type, status=status)


def index(request):
    
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode())
        except:
            response = {}
            return render_to_json_response(response)

        for key in ('email', 'name', 'message'):
            if not data.get(key):
                print(key, 'msising', data)
                return render_to_json_response({})

        name = data['name']
        email = data['email']
        message = data['message']
        message = "Name: %s\nEmail: %s\n\n%s" % (name, email, message)
        subject = '{} has left a message on brixton-timeline'.format(name)
        from_ = settings.CONTACT_FROM_EMAIL
        to = settings.CONTACT_TO_EMAIL
        if not isinstance(to, list):
            to = [to]
        msg = EmailMessage(subject, message, from_, to, reply_to=[email])
        msg.send(fail_silently=True)
        return render_to_json_response({"sent": True})
    return redirect('/')