import json
import traceback

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseBadRequest
from .api_methods import api_call_method, api_get_documentation
from .api_errors import *


def view_methods(request):
    methods = []

    def __make_param(p):
        return {
            "name": p["name"],
            "type": p["type"],
            "description": p["description"],
            "required": p["required"]
        }

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


def call_method(request, method_name):
    if request.method == "GET":
        params = request.GET
    elif request.method == "POST":
        params = request.POST
    else:
        return HttpResponseBadRequest()

    out = api_call_method(method_name, params)

    response = HttpResponse(json.dumps(out, ensure_ascii=False))
    response.headers["Content-type"] = "application/json; charset=utf-8"
    return response
