import json
import os
import pathlib
import time

import requests
from requests.auth import HTTPBasicAuth

"""
Explanation: 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 ortho_analytic_4b PSScene 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.
End of explanation
"""


# 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'

"""
Explanation: Authenticating
End of explanation
"""


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

"""
Explanation: Curl example
To check your orders list and make sure you have the permissions you need, uncomment the following line to run curl
End of explanation
"""


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

"""
Explanation: 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 AOI reference.
End of explanation
"""


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

"""
Explanation: Now we will list the orders we have created thus far. Your list may be empty if you have not created an order yet.
End of explanation
"""


# 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":"PSScene",
         "product_bundle":"analytic_udm2"
      }
   ],
}

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)

"""
Explanation: Ordering
In this example, we will order two PSScene ortho_analytic_4b images. For variations on this kind of order, see Ordering Data.
In this order, we request an analytic bundle. A bundle is a group of assets for an item. The analytic_udm2 bundle for the  PSScene item contains 3 assets: the ortho-analytic image, the ortho-analytic xml file, and the ortho-udm2. See the Product bundles reference to learn about other bundles and other items.
Place Order
End of explanation
"""


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

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']

"""
Explanation: Cancel an Order
End of explanation
"""


# 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)

"""
Explanation: Poll for Order Success
End of explanation
"""


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

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

"""
Explanation: View Results
End of explanation
"""


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)

"""
Explanation: Download
Downloading each asset individually
End of explanation
"""


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)

"""
Explanation: 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.
End of explanation
"""


