import json

from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from . import generate as stickersheet
from .models import Tikette, Tikategory

CORS={'access-control-allow-origin': '*'}

def index(request):
    tikettes = [{
        'title': x.title,
        'category': x.category.name,
        'sticker': x.svg.name,
        'landscape': x.category.landscape,
        'subs': {x.name: x.default for x in x.category.subs.all()},
        } for x in Tikette.objects.all()]
    return JsonResponse({'status': 'ok', 'tikettes': tikettes}, headers=CORS)

@csrf_exempt
def generate(request):
    if request.method != "POST":
        return JsonResponse({'status': 'notok', 'message': 'this isn\'t the way'})

    payload = json.loads(request.body)
    pdfpath = stickersheet.generate(payload, out_dir=settings.TIKETTE_OUT_DIR)

    return JsonResponse({'status': 'ok', 'file': pdfpath}, headers=CORS)
