# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Module to implement the JSON-RPC protocol.

This module uses xmlrpclib as the base and only overrides those
portions that implement the XML-RPC protocol. These portions are rewritten
to use the JSON-RPC protocol instead.

When large portions of code need to be rewritten the original code and
comments are preserved. The intention here is to keep the amount of code
change to a minimum.

This module only depends on default Python modules. No third party code is
required to use this module.
"""
import json
import urllib
import xmlrpclib as _base

__version__ = '1.0.0'
gzip_encode = _base.gzip_encode
gzip = _base.gzip


class Error(Exception):

  def __str__(self):
    return repr(self)


class ProtocolError(Error):
  """Indicates a JSON protocol error."""

  def __init__(self, url, errcode, errmsg, headers):
    Error.__init__(self)
    self.url = url
    self.errcode = errcode
    self.errmsg = errmsg
    self.headers = headers

  def __repr__(self):
    return (
        '<ProtocolError for %s: %s %s>' %
        (self.url, self.errcode, self.errmsg))


class ResponseError(Error):
  """Indicates a broken response package."""
  pass


class Fault(Error):
  """Indicates a JSON-RPC fault package."""

  def __init__(self, code, message):
    Error.__init__(self)
    if not isinstance(code, int):
      raise ProtocolError('Fault code must be an integer.')
    self.code = code
    self.message = message

  def __repr__(self):
      return (
          '<Fault %s: %s>' %
          (self.code, repr(self.message))
          )


def CreateRequest(methodname, params, ident=''):
  """Create a valid JSON-RPC request.

  Args:
    methodname: The name of the remote method to invoke.
    params: The parameters to pass to the remote method. This should be a
        list or tuple and able to be encoded by the default JSON parser.

  Returns:
    A valid JSON-RPC request object.
  """
  request = {
      'jsonrpc': '2.0',
      'method': methodname,
      'params': params,
      'id': ident
      }

  return request


def CreateRequestString(methodname, params, ident=''):
  """Create a valid JSON-RPC request string.

  Args:
    methodname: The name of the remote method to invoke.
    params: The parameters to pass to the remote method.
        These parameters need to be encode-able by the default JSON parser.
    ident: The request identifier.

  Returns:
    A valid JSON-RPC request string.
  """
  return json.dumps(CreateRequest(methodname, params, ident))


def CreateResponse(data, ident):
  """Create a JSON-RPC response.

  Args:
    data: The data to return.
    ident: The response identifier.