import requests
import logging
import json


def get_function_signature_from_4bytes(hex_signature):
    """
    Requests the function signature from 4byte-directory based on the hex_signature to get the text_signature

    Args:
      hex_signature: the signature of the function as hex value

    Returns:
      signature of the function as text
    """

    resp = requests.get('https://www.4byte.directory/api/v1/signatures/?hex_signature=' + hex_signature)
    if resp.status_code != 200:
        # This means something went wrong.
        logging.error("something went wrong at 4byte-directory api call" + str(resp.status_code))
        return hex_signature

    json_data = json.loads(resp.text)
    for sig in json_data['results']:
        logging.info("got function signature: " + sig['text_signature'])
        return sig['text_signature']

    return hex_signature