import os
import ast
import requests, gspread
import numpy as np
import matplotlib.pyplot as plt

from oauth2client.client import SignedJwtAssertionCredentials
from mpl_toolkits.basemap import Basemap

#Google Authorisation section and getting a worksheet from Google Spreadsheet

def authenticate_google_docs():
    f = file(os.path.join('SSI Network Graphics-3357cb9f30de.p12'), 'rb')
    SIGNED_KEY = f.read()
    f.close()
    scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds']
    credentials = SignedJwtAssertionCredentials('devasena.prasad@gmail.com', SIGNED_KEY, scope)

    data = {
        'refresh_token' : '1/NM56uCG7uFT6VVAAYX3B5TbcMk43wn1xE8Wr-7dsb7lIgOrJDtdun6zK6XiATCKT',
        'client_id' : '898367260-pmm78rtfct8af7e0utis686bv78eqmqs.apps.googleusercontent.com',
        'client_secret' : 'Cby-rjWDg_wWTSQw_8DDKb3v',
        'grant_type' : 'refresh_token',
    }

    r = requests.post('https://accounts.google.com/o/oauth2/token', data = data)
    credentials.access_token = ast.literal_eval(r.text)['access_token']

    gc = gspread.authorize(credentials)
    return gc

gc_ret = authenticate_google_docs()
sh = gc_ret.open_by_url('https://docs.google.com/spreadsheets/d/13_ZIdeF7oS0xwp_nhGRoVTv7PaXvfLMwVxvgt_hNOkg/edit#gid=383409775')

worksheet_list = sh.worksheets() # Get list of worksheets


#Print the names of first and second worksheets
print "First 2 worksheets of Fellows data Google spreadsheet are:", worksheet_list[0], worksheet_list[1]

# Get all values from the first, seventh and eight columns of Sample datset
values_list_names = worksheet_list[0].col_values(1)
destination_lat_values = worksheet_list[0].col_values(7)
destination_lon_values = worksheet_list[0].col_values(8)

print "Names of SSI fellows are:",values_list_names
print "Destination Latitude values are:",destination_lat_values
print "Destination Longitude values are:", destination_lon_values

# get all values from first, fourth and fifth columns of Home Institutions worksheet
fellows_list_names = worksheet_list[1].col_values(1)
home_lat_values = worksheet_list[1].col_values(4)
home_lon_values = worksheet_list[1].col_values(5)

print "Names of SSI fellows are:",fellows_list_names
print "Home Institution Latitude values are:",home_lat_values
print "Home Institution Longitude values are:", home_lon_values

# create new figure, axes instances.
fig=plt.figure()
ax=fig.add_axes([0.1,0.1,0.8,0.8])
# setup mercator map projection.
m = Basemap(llcrnrlon=-150.,llcrnrlat=-40.,urcrnrlon=150.,urcrnrlat=80.,\
            rsphere=(6378137.00,6356752.3142),\
            resolution='l',projection='merc',\
            lat_0=40.,lon_0=-20.,lat_ts=20.)

#Plotting fellows routes on map
print "No. of unique fellows are:", (len(worksheet_list[1].col_values(1))-1)

colcode = ['b','r','g','y','m','c','k','w']

i = 1
j = 1

print "No. of destination entries in the Sample datasheet:", (len(worksheet_list[0].col_values(7))-1)

while i < len(worksheet_list[1].col_values(1)):
    while j < len(worksheet_list[0].col_values(7)):
         m.drawgreatcircle(float(home_lon_values[i]),float(home_lat_values[i]),float(destination_lon_values[j]),float(destination_lat_values[j]),linewidth=2,color=colcode[i-1])
         j = j + 1
    i = i + 1

#label=fellows_list_names[i] 
   
m.drawcoastlines()
m.fillcontinents()
# draw parallels
m.drawparallels(np.arange(10,90,20),labels=[1,1,0,1])
# draw meridians
m.drawmeridians(np.arange(-180,180,30),labels=[1,1,0,1])
ax.set_title('SSI Fellows Impact')

plt.legend()
plt.show()

