import requests

url = 'https://api.projectoxford.ai/vision/v1.0/describe'
key = 'MICROSOFT_COMPUTER_VISION_API_KEY' 

'''
Uses the microsoft computer vision API in order to find an appropriate name 
for an image.
'''
def getImageName(data):
	headers = dict()
	headers['Ocp-Apim-Subscription-Key'] = key
	headers['Content-Type'] = 'application/octet-stream'
	r = processRequest(None, data, headers, None)
	return r['description']['tags'][0] + '.' + r['metadata']['format'].lower()

'''
Request wrapper taken from the Python SDK for Computer Vision API
https://github.com/Microsoft/Cognitive-Vision-Python/blob/master/Jupyter%20Notebook/Computer%20Vision%20API%20Example.ipynb
'''
def processRequest( json, data, headers, params ):

    """
    Helper function to process the request to Project Oxford

    Parameters:
    json: Used when processing images from its URL. See API Documentation
    data: Used when processing image read from disk. See API Documentation
    headers: Used to pass the key information and the data type request
    """

    retries = 0
    result = None

    while True:

        response = requests.request( 'post', url, json = json, data = data, headers = headers, params = params )

        if response.status_code == 429: 

            print( "Message: %s" % ( response.json()['error']['message'] ) )

            if retries <= _maxNumRetries: 
                time.sleep(1) 
                retries += 1
                continue
            else: 
                print( 'Error: failed after retrying!' )
                break

        elif response.status_code == 200 or response.status_code == 201:

            if 'content-length' in response.headers and int(response.headers['content-length']) == 0: 
                result = None 
            elif 'content-type' in response.headers and isinstance(response.headers['content-type'], str): 
                if 'application/json' in response.headers['content-type'].lower(): 
                    result = response.json() if response.content else None 
                elif 'image' in response.headers['content-type'].lower(): 
                    result = response.content
        else:
            print( "Error code: %d" % ( response.status_code ) )
            print( "Message: %s" % ( response.json()) )

        break
        
    return result
