import requests
import json

# API are accessed with an API key.
# Please refer to documentation if you need to get an API key.
apiKey=raw_input("Paste your API key: ")

# AUTHENTICATION ------------------------------------------------------------------------------------------------
# Build the Authentication Request, and run it.
urlAuth = "https://authenticate.foundation.api.oneatlas.airbus.com/auth/realms/IDP/protocol/openid-connect/token"

payloadAuth = "grant_type=api_key&client_id=IDP&apikey="+apiKey
headersAuth = {
    'Content-Type': "application/x-www-form-urlencoded",
    'Cache-Control': "no-cache"
    }

responseAuth = requests.request("POST", urlAuth, data=payloadAuth, headers=headersAuth)
jsonAuth = json.loads(responseAuth.text)

# Local AuthenticationReturn.json file contains the JSON result of the Authentication Request
fAuth=open('./AuthenticationReturn.json', 'wt')
fAuth.write(json.dumps(jsonAuth, indent=4))
fAuth.close()

# The result of the authentication is a Bearer IDP token that will be used for authentication in the following requests.
idpToken=jsonAuth["access_token"]

# SEARCH FOR AN IMAGE WITHIN THE CATALOGUE, WITH PARAMETERS ----------------------------------------------------
# Build the Search Request, and run it
url = "https://search.federated.geoapi-airbusds.com/api/v1/search"

payload = "{\r\n  \"bbox\": [\r\n    1.18,\r\n    43.52,\r\n    1.25,\r\n    43.56\r\n  ],\r\n  \"constellation\": [\r\n    \"SPOT\"\r\n  ],\r\n  \"acquisitionDate\": \"[2016-07-01,2016-07-31T23:59:59]\",\r\n  \"incidenceAngle\": \"20]\",\r\n  \"cloudCover\": \"10]\",\r\n  \"count\": 10,\r\n  \"startPage\": 1\r\n}"
headers = {
    'Authorization': "Bearer "+idpToken,
    'Content-Type': "application/json",
    'Cache-Control': "no-cache"
    }

response = requests.request("POST", url, data=payload, headers=headers)

# Write down the JSON result into a local SearchReturn.json file to read it.
jsonResponse = json.loads(response.text)
# write the JSON result as a file
fsearch=open('./SearchReturn.json', 'wt')
fsearch.write(json.dumps(jsonResponse, indent=4))
fsearch.close()

# SEARCH FOR THE IMAGE FOUND IN RETURN -------------------------------------------------------------------------
# Parse the Result of the Search to find the Picture Download Endpoint.
for feature in jsonResponse["features"]:
    # This example returns one Segment only (This loop plays once).
    # But this Code would display all the LARGE images found by the Search Request.
    sourceId=feature["properties"]["sourceId"]
    imageId=feature["id"];
    for image in feature["quicklooks"]:
        # For all the formats of this Segment, find the LARGE one(s).
        if image["size"]=="LARGE":
            urlImage=image["image"]
            querystring = {"size":"LARGE"}
            headersImage = {
                'Authorization': "Bearer "+idpToken,
                'Cache-Control': "no-cache"
            }
            responseImage = requests.request("GET", urlImage, headers=headersImage)
            # The result is stored into a local JPG picture.
            with open('./Image_'+sourceId+'.jpg', 'wb') as f:
                f.write(responseImage.content)
                f.close()
                ftext=open('./Image_'+sourceId+'.json', 'wt')
                ftext.write(json.dumps(feature, indent=4))
                ftext.close()

