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 .planche import generate as stickersheet
from .models import Tikette, Tikategory

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


def quirk_bold_allergens(ingredients):
    out = []
    for ing in (x.strip() for x in ingredients.split(',')):
        if ing.startswith('*'):
            out.append(f'<tspan style="font-weight:bold">{ing[1:]}</tspan>')
        else:
            out.append(ing)
    return ", ".join(out)


def get_list(request):
    tikettes = [{
        'id': x.id,
        'title': x.title,
        'category': x.category.name,
        'prototempalte': x.category.prototempalte.name,
        'landscape': x.category.landscape,
        'designation': x.designation,
        'ingredients': quirk_bold_allergens(x.ingredients),
        'description': x.description,
        'ab': x.ab,
        'color': x.color,
        '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)


def get_categories(request):
    tikats = [{
        'id': x.id,
        'name': x.name,
        } for x in Tikategory.objects.all()]
    return JsonResponse({'status': 'ok', 'tikats': tikats}, 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)

    subs = dict(payload['subs'])
    for key in ('designation', 'ingredients', 'description', 'color', 'AB'):
        subs[key] = payload[key]

    pdfpath = stickersheet.generate(template=payload['template'], subs=subs,
                                    out_dir=settings.TIKETTE_OUT_DIR,
                                    landscape=payload['landscape'])

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


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

    payload = json.loads(request.body)
    tikette = Tikette(**payload)
    tikette.save()

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


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

    payload = json.loads(request.body)
    Tikette.objects.get(id=payload["id"]).delete()

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