import json
import traceback

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


def view_methods(request):
    return render(request, 'api/index.html', {'api_methods': api_methods})


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

    try:
        if method_name in api_methods:
            out = api_methods[method_name]["func"](params)
            if out is None:
                raise Exception(API_ERROR_INTERNAL_ERROR, "method returned null object")
        else:
            raise Exception(API_ERROR_METHOD_NOT_FOUND)
    except Exception as ex:
        traceback.print_exc()
        out = make_error_object(ex)

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