API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
TOPIC = 'bluemix'

import requests
import numpy as np
import pandas as pd
import folium
from IPython.display import HTML

pd.set_option('display.max_colwidth', 500)

"""
Explanation: Upcoming Meetups
This notebook queries meetup.com for upcoming events matching a topic and having at least 3 RSVPs. It then gives a summary of those meetups in tabular and map form.
To run this notebook:

pip install folium pandas numpy requests if you haven't already.
Set your API key value
Set your search topic.
Run All.
End of explanation
"""


r = requests.get("https://api.meetup.com/2/open_events", params={'topic': TOPIC, 'key': API_KEY})

r.raise_for_status()

df = pd.DataFrame(r.json()['results'])

"""
Explanation: Request the open events from the Meetup.com API.
End of explanation
"""


df['localtime'] = pd.to_datetime(df.time+df.utc_offset, unit='ms')

"""
Explanation: Convert the times since epoch in $\mu s$ to datetime objects, accounting for timezone offset. Hereafter, the times will be local to the meetup venue.
End of explanation
"""


def text_location(venue):
    '''
    Return city, state, country, omitting any piece that isn't available.
    '''
    loc = []
    if pd.isnull(venue): return ''
    if 'city' in venue:
        loc.append(venue['city'])
    if 'state' in venue:
        loc.append(venue['state'])
    if 'country' in venue:
        loc.append(venue['country'].upper())
    return ', '.join(loc)

df['location'] = df.venue.apply(text_location)

"""
Explanation: Create a human readable description of the location down to the city level, if possible.
End of explanation
"""


df['link_name'] = df.apply(lambda row: '<a href="{row[event_url]}" target="_blank">{row[name]}</a>'.format(row=row), axis=1)

"""
Explanation: Turn the event name into a link to its page on meetup.com.
End of explanation
"""


HTML('<h2>Table of Upcoming <em>{}</em> Meetups</h2>'.format(TOPIC))

HTML(df[['link_name', 'localtime', 'location', 'yes_rsvp_count']].to_html(escape=False))

HTML('<h2>Map of Upcoming <em>{}</em> Meetups</h2>'.format(TOPIC))

def map_marker(row):
    '''
    Returns a dictionary with the lat/long location of an event venue as well
    as a popup containing a link to its meetup.com page. Filters events
    with no valid lat/long location.
    '''
    if pd.isnull(row['venue']): return None
    lat = row['venue'].get('lat', 0.)
    lon = row['venue'].get('lon', 0.)
    if lat == 0 or lon == 0: return None
    return dict(
        location=[lat, lon],
        popup=row['link_name']
    )

m = folium.Map(location=[45, -40], zoom_start=2)

for i, row in df.iterrows():
    marker = map_marker(row)
    if marker:
        m.simple_marker(**marker)

m._build_map()

"""
Explanation: Use the HTML output feature instead of static markup so that the topic name appears.
End of explanation
"""


HTML('<iframe srcdoc="{srcdoc}" style="width: 100%; height: 510px; border: none"></iframe>'.format(srcdoc=m.HTML.replace('"', '&quot;')))

"""
Explanation: Idea: We might want show the venues of RSVPs in realtime on a map along with the locations of our meetups.
End of explanation
"""


