import os

# if your Planet API Key is not set as an environment variable, you can paste it below
API_KEY = os.environ.get('PL_API_KEY', 'PASTE_YOUR_KEY_HERE')
# alternatively, you can just set your API key directly as a string variable:
# API_KEY = "YOUR_PLANET_API_KEY_HERE"
# construct auth tuple for use in the requests library
BASIC_AUTH = (API_KEY, '')

"""
Explanation: Planet Analytics API Tutorial
Summarizing Feeds and Subscriptions
This notebook demonstrates how to describe available Analytics Feeds and Subscriptions with the Planet Analytic API.
Setup
To use this notebook, you need to have the following:
- A Planet account with access to the Analytics API
- A Planet API Key
Set API Key
End of explanation
"""


BASE_URL = "https://api.planet.com/analytics/"

"""
Explanation: Set the base url for the Planet Analytic Feeds product
See the Analytics API Docs for more details.
End of explanation
"""


import requests

feed_list_url = f'{BASE_URL}feeds?limit=1'
resp = requests.get(feed_list_url, auth=BASIC_AUTH)
if resp.status_code == 200:
    print('Yay, you can access the Analytics API')
else:
    print('Something is wrong:', resp.content)

"""
Explanation: Test API Connection
End of explanation
"""


limit = 1000
feed_list_url = f'{BASE_URL}feeds?limit={limit}'
print(f'Feeds endpoint: {feed_list_url}')
resp = requests.get(feed_list_url, auth=BASIC_AUTH)
feeds = resp.json()['data']
feed_count = len(feeds)
print(f'Available feeds: {feed_count}')
if feed_count >= limit:
    print('More feeds are probably available through pagination links')
    print(resp.json()['links'])

"""
Explanation: Summarizing Feeds
In this section, we will see describe the available feeds.
How many feeds are there?
End of explanation
"""


from pprint import pprint
pprint(feeds[0])

"""
Explanation: Inspecting feed metadata
End of explanation
"""


import pandas as pd
# bump this up in case there are many available feeds to display
pd.options.display.max_rows = 1000
# make a dataframe from the feeds json data
df = pd.DataFrame(feeds)
# instead of including the entire source and target dicts, make columns for the types
df['targetType'] = df['target'].map(lambda t: t['type'])
df['sourceType'] = df['source'].map(lambda t: t['type'])
df[['id', 'title', 'description', 'sourceType', 'targetType', 'created', 'updated']]


"""
Explanation: Some of the fields include:
- id: this is a unique identifier for a feed
- title: a human friendly name for the feed
- description: more detail text about the feed
- created: timestamp for when the feed was originally created
- updated: timestamp for when the feed was last modified
- source: a blob describing the imagery on which the feed is based
- target: a blob describing the feed's output format
- links: a list of blobs containing urls to related resources
Showing all available feeds in a table
We can use a pandas DataFrame to summarize the available feeds.
End of explanation
"""


limit = 1000
subscriptions_url = f'{BASE_URL}subscriptions?limit={limit}'
print(f'Subscriptions endpoint: {subscriptions_url}')
resp = requests.get(subscriptions_url, auth=BASIC_AUTH)
subs = resp.json()['data']
sub_count = len(subs)
print(f'Available subscriptions: {sub_count}')
if sub_count >= limit:
    print('More subscriptions are probably available through pagination links')
    print(resp.json()['links'])

"""
Explanation: Summarizing Subscriptions
Now that we know about available feeds, let's check out available subscriptions.
End of explanation
"""


pprint(subs[0])

"""
Explanation: What's in a subscription?
End of explanation
"""


df = pd.DataFrame(subs)
df[['id', 'title', 'description', 'feedID', 'startTime', 'endTime', 'created', 'updated']]

"""
Explanation: Subscriptions also have id, title, description, created, and updated fields.
Additionally, there are fields for:
- feedID: which feed this subscription is for
- startTime: timestamp for the subscription's beginning
- endTime: timestamp for the subscription's ending
- geometry: spatial area of interest to which the subscription has access
Important: 
Subscriptions will only get results for source imagery observed between the startTime and endTime within the specified geometry.
created and updated refer to when the subscription itself was set up or modified and do not impact results that show up for the subscription. 
startTime and endTime do limit feed results for the subscription.
Showing all available subscriptions
End of explanation
"""


feed_id = feeds[0]['id']
feed_title = feeds[0]['title']
print(feed_title)
print('id:', feed_id)

filtered_subscriptions_url = f'{BASE_URL}subscriptions?feedID={feed_id}'
print('url:', filtered_subscriptions_url)
resp = requests.get(filtered_subscriptions_url, auth=BASIC_AUTH)
filtered_subs = resp.json()['data']
filtered_sub_count = len(filtered_subs)
print(f'You have access to {filtered_sub_count} subscriptions for feed {feed_id} ({feed_title})')

"""
Explanation: Filtering subscriptions by feed
End of explanation
"""


# get the latest subscription's geometry
subscription = subs[0]
geom = subscription['geometry']
pprint(geom)

# make a map, and draw the subscription geometry
from ipyleaflet import Map, GeoJSON
lon, lat = geom['coordinates'][0][0]

m = Map(center=(lat, lon), zoom=8)
geo_json = GeoJSON(data=subscription['geometry'], style = {'color': 'blue', 'opacity':1, 'weight':1.9, 'dashArray':'9', 'fillOpacity':0.1})
m.add_layer(geo_json)
m

"""
Explanation: Inspecting a subscription's geometry
Subscriptions have a spatial area of interest described by a geojson geometry. We can visualize the area of interest for a subscription on a map.
End of explanation
"""


