# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Ordering and Delivery
#
# This notebook demonstrates ordering and download with the orders api. In this notebook, we check authentication by requesting an orders list, then we create an order for two Analytic `PSScene4Band` images. We poll for order success then download images individually. And finally, we create, poll, and download the same order delivered as a single zip file.
#
# Reference information can be found at [Ordering & Delivery](https://developers.planet.com/docs/orders/ordering-delivery/).

# +
import json
import os
import pathlib
import time

import requests
from requests.auth import HTTPBasicAuth
# -

# ## Authenticating

# API Key stored as an env variable
PLANET_API_KEY = os.getenv('PL_API_KEY')

orders_url = 'https://api.planet.com/compute/ops/orders/v2'

# ### Curl example
#
# To check your orders list and make sure you have the permissions you need, uncomment the following line to run `curl`

# !curl -L -H "Authorization: api-key $PLANET_API_KEY" $orders_url

# ### Requests example
#
# In this notebook, we will be using `requests` to communicate with the orders v2 API. First, we will check our orders list to make sure authentication and communication is working as expected.
#
# We want to get a response code of `200` from this API call. To troubleshoot other response codes, see the [List Orders](https://developers.planet.com/docs/orders/reference/#operation/listOrders) AOI reference.

auth = HTTPBasicAuth(PLANET_API_KEY, '')
response = requests.get(orders_url, auth=auth)
response

# Now we will list the orders we have created thus far. Your list may be empty if you have not created an order yet.

orders = response.json()['orders']
len(orders)

# ## Ordering
#
# In this example, we will order two `PSScene4Band` analytic images. For variations on this kind of order, see [Ordering Data](https://developers.planet.com/docs/orders/ordering-delivery/#ordering-data_1).
#
# In this order, we request an `analytic` bundle. A bundle is a group of assets for an item. The `analytic` bundle for the  `PSScene4Band` item contains 3 assets: the analytic image, the analytic xml file, and the udm. See the [Product bundles reference](https://developers.planet.com/docs/orders/product-bundles-reference/) to learn about other bundles and other items.
#
# ### Place Order

# set content type to json
headers = {'content-type': 'application/json'}

request = {  
   "name":"simple order",
   "products":[
      {  
         "item_ids":[  
            "20151119_025740_0c74",
            "20151119_025741_0c74"
         ],
         "item_type":"PSScene4Band",
         "product_bundle":"analytic"
      }
   ],
}


def place_order(request, auth):
    response = requests.post(orders_url, data=json.dumps(request), auth=auth, headers=headers)
    print(response)
    order_id = response.json()['id']
    print(order_id)
    order_url = orders_url + '/' + order_id
    return order_url


order_url = place_order(request, auth)

# ### Cancel an Order

# report order state
requests.get(order_url, auth=auth).json()['state']

oid = oids[0]
response = requests.put(order_url, auth=auth)
response

# report order state - it could take a little while to cancel
requests.get(order_url, auth=auth).json()['state']

# ### Poll for Order Success

# re-order since we canceled our last order
order_url = place_order(request, auth)


# +
def poll_for_success(order_url, auth, num_loops=30):
    count = 0
    while(count < num_loops):
        count += 1
        r = requests.get(order_url, auth=auth)
        response = r.json()
        state = response['state']
        print(state)
        end_states = ['success', 'failed', 'partial']
        if state in end_states:
            break
        time.sleep(10)
        
poll_for_success(order_url, auth)
# -

# ### View Results

r = requests.get(order_url, auth=auth)
response = r.json()
results = response['_links']['results']

[r['name'] for r in results]


# ## Download
#
# ### Downloading each asset individually

def download_results(results, overwrite=False):
    results_urls = [r['location'] for r in results]
    results_names = [r['name'] for r in results]
    print('{} items to download'.format(len(results_urls)))
    
    for url, name in zip(results_urls, results_names):
        path = pathlib.Path(os.path.join('data', name))
        
        if overwrite or not path.exists():
            print('downloading {} to {}'.format(name, path))
            r = requests.get(url, allow_redirects=True)
            path.parent.mkdir(parents=True, exist_ok=True)
            open(path, 'wb').write(r.content)
        else:
            print('{} already exists, skipping {}'.format(path, name))


download_results(results)

# ### Downloading as a single zip
#
# To download all of the order assets as a single zip, the order request needs to be changed slightly with delivery instructions. After that, polling and downloading are the same.

zip_delivery = {"delivery": {"single_archive": True, "archive_type": "zip"}}
request_zip = request.copy()
request_zip.update(zip_delivery)
request_zip

order_url = place_order(request_zip, auth)

poll_for_success(order_url, auth)

r = requests.get(order_url, auth=auth)
response = r.json()
results = response['_links']['results']

download_results(results)

StarcoderdataJupyterScriptsDedupFiltered