import hashlib

try:
    import ujson as json
except ImportError:
    import json


def update_object_hash(m, obj):
    r = json.dumps(obj, sort_keys=True)
    m.update(r.encode())
    return m


def prov_key(job_msg, extra=None):
    """Retrieves a MD5 sum from a function call. This takes into account the
    name of the function, the arguments and possibly a version number of the
    function, if that is given in the hints.
    This version can also be auto-generated by generating an MD5 hash from the
    function source. However, the source-code may not always be reachable, or
    the result may depend on an external process which has its own
    versioning."""
    m = hashlib.md5()
    update_object_hash(m, job_msg['data']['function'])
    update_object_hash(m, job_msg['data']['arguments'])

    if 'version' in job_msg['data']['hints']:
        update_object_hash(m, job_msg['data']['hints']['version'])

    if extra is not None:
        update_object_hash(m, extra)

    return m.hexdigest()
