from staff.django_rpc import RpcRequest
from xmlrpc.client import dumps, loads, Fault, APPLICATION_ERROR


def serialize(response, request):
    if response.error:
        if getattr(response.error, 'error', None):
            response.error = response.error.error
        else:
            response.error = str(response.error)
        r = dumps(Fault(APPLICATION_ERROR, response.error))
    else:
        r = dumps((response.result,), methodresponse=True, allow_none=True)
    return {
        'response': r,
        'mime': 'text/xml',
    }


def deserialize(request):
    data = loads(request.body)
    return RpcRequest(method=data[1], params=data[0])
