from django.http import HttpResponse
from tikz.models import Tikz
import json

# ==========================  Ajax ======================================


def ajax(request, commandstr):
    CT = "application/x-www-form-urlencoded; charset=UTF-8"
    is_ajax = request.META.get("CONTENT_TYPE") == CT
    if is_ajax and request.method == 'POST':
        args = dict()
        for k, v in request.POST.items():
            args[k] = v[0] if (isinstance(v, list) and len(v) == 1) else v

        path = request.get_full_path().split('/')[3:-1]
        command = path[0]
        args['path'] = path
        args['command'] = command
        setattr(request, 'cleaned_data', args)
        try:
            res = execute(request, command)
        except Exception as eeps:
            res = request.cleaned_data
            res['exception'] = str(eeps)
        return HttpResponse(json.dumps(res))
    return HttpResponse(json.dumps(dict(ct=request.META.get("CONTENT_TYPE"))))


def execute(request, command):
    if command == 'image':
        return image(request)
    raise Exception(f"Unknown command: {command}")


def image(request):
    args = request.cleaned_data
    action = args['action']
    tz = Tikz.objects.get(id=int(args['pk']))
    d = dict(pk=tz.id, action=action)
    if action == 'hide':
        tz.hide = True
        tz.save()
        d['result'] = f"Hid image {tz.id}"
    elif action == 'delete':
        d['result'] = f"Deleted image {tz.id}"
        tz.delete()

    return d
