from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
from .dispatcher import dispatch, methods_list


@csrf_exempt
def handle_rpc(request, type=None):
    """Handles XML-RPC requests. All XML-RPC calls should be forwarded here

    request
        The HttpRequest object that carries the XML-RPC call. If this is a
        GET request, nothing will happen (we only accept POST requests)
    """
    if request.method != 'POST' and not request.GET.get('json', None):
        template = getattr(settings, 'RPC_TEMPLATE', 'django_rpc/index.html')
        r = methods_list()
        methods = []
        for app in r:
            for m in r[app]:
                methods.append({'name': app+'.'+m, 'doc': r[app][m]['func'].__doc__})
        return render_to_response(template, {'type': type, 'methods': methods})
    else:
        r = dispatch(type, request)
        return HttpResponse(r['response'], content_type=r['mime'])
