import json
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt

from .api_methods import api_call_method, api_get_documentation


def view_methods(request):
    methods = api_get_documentation()
    return render(request, 'index.html', {'api_methods': methods})


def _default_serializer(obj):
    try:
        return obj.to_json()
    except Exception:
        return str(obj)


async def call_method(request, method_name):
    if request.method == "GET":
        params = request.GET
    elif request.method == "POST":
        params = request.POST
    else:
        return HttpResponseBadRequest()
    api_params = {}
    for p in params:
        # защита от нескольких параметров с одним именем
        api_params[p] = params[p]

    out = await api_call_method(request, method_name, api_params)

    if isinstance(out, dict):
        response = HttpResponse(json.dumps(out, default=_default_serializer, ensure_ascii=False, indent=4))
        response.headers["Content-type"] = "application/json; charset=utf-8"
        return response
    else:
        return out
