# -* encoding: utf-8 -*-

import json

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.core.cache import cache

import models
import app_settings

def handle(content, name):
    content_block, created = models.ContentBlock.objects.get_or_create(name=name)
    if not content.strip():
        content_block.delete()
        cache.set(app_settings.cache_key(name), False,
                app_settings.EDITOR_CACHE_TIMEOUT)
    else:
        content_block.content = content
        cache.set(app_settings.cache_key(name), content,
                app_settings.EDITOR_CACHE_TIMEOUT)
        content_block.save()

@csrf_exempt
def handler(request):
    if request.method == 'PUT' and request.user.has_perm('editor.edit_site'):
        try:
            kwargs = json.loads(request.body)
        except ValueError:
            pass
        handle(**kwargs)
    return HttpResponse()

