# Load the API key for darksky
with open('darksky_key.txt') as f:
    key = f.read()

from darksky import forecast

coords_grenoble = ( 45.166672, 5.71667 ) 

data = forecast(key, *coords_grenoble, units='si', lang='fr' )

type( data )

data['currently']['temperature']

len( data['daily']['data'] )

T = [ hour.temperature for hour in data.hourly ]

print( len(T) )

plt.plot( T )

from datetime import datetime as dt

t = dt(2017, 6, 10).isoformat()  # year month day hour ...

exclude = ['currently', 'minutely', 'daily', 'flags']
data = forecast(key, *coords_grenoble, units='si', lang='fr', time=t, exclude=exclude)

records = data['hourly']['data']

records

dropcols = ['icon', 'apparentTemperature', 'ozone', 'summary', 'uvIndex', 'windGust', 'dewPoint',
               'precipProbability', 'visibility', 'pressure', 'humidity', 'precipType']

df = pd.DataFrame.from_records(records, index='time')

df.drop(dropcols, axis=1, level=None, inplace=True, errors='ignore')

len(records)

df.index = pd.to_datetime(df.index ,unit='s')

df

T = [ hour.temperature for hour in data.hourly ]

print( len(T) )

di = [{'t':45, 'value':4}, {'t':78, 'value':77}]

import pandas as pd

plt.plot( T );

windSpeed = [ hour.windSpeed for hour in data.hourly ]

plt.plot( windSpeed );

cloudCover = [ hour.cloudCover for hour in data.hourly ]

plt.plot( cloudCover );

data.hourly[4].temperature

timeindex = pd.to_datetime('today')[ hour.time for hour in data.hourly ]

[ hour['temperature'] for hour in data.hourly ]

import pandas as pd

# voir https://darksky.net/dev/docs/response
datalabels = ['temperature', 'cloudCover', 'precipIntensity', 'windSpeed' , 'windBearing']

def buildDFdaily(day, coords):
    data = forecast(key, *coords, units='si', lang='fr', time=day)
    
    timeindex = pd.to_datetime( [ hour.time for hour in data.hourly ],  unit='s' , origin='unix' )
    
    dailydata = {}
    for label in datalabels:
        dailydata[label] = [ dataeveryhour[label] for dataeveryhour in data.hourly ]
        
    df = pd.DataFrame(dailydata, index=timeindex )
    return df

df = buildDFdaily( t, coords_grenoble )

df

df.plot()

"""
Explanation: Get weather data
Darksky data
https://darksky.net/
https://github.com/lukaskubis/darkskylib
pip install darkskylib
End of explanation
"""


import weatherfeed as wf

coords_grenoble = (45.1973288, 5.7139923) #(45.1973288, 5.7103223)

startday, lastday = pd.to_datetime('10/06/2017', format='%d/%m/%Y'), pd.to_datetime('now')
#pd.to_datetime('01/07/2017', format='%d/%m/%Y')

EXCLUDE = [] #[ 'minutely', 'daily', 'flags']  # from the query

COL2DROP = ['icon', 'apparentTemperature', 'ozone', 'uvIndex', 'windGust', 'dewPoint',
               'precipProbability', 'visibility', 'pressure', 'humidity', 'precipType']

coords = coords_grenoble

daterange = pd.date_range(start=startday, end=lastday,  freq='D', normalize=True)
daterange



records = []
for day in daterange:

    day_iso = day.isoformat()

    print('%i, '%day.day, end='')

    data = forecast(KEY, *coords, units='si', lang='fr', \
         time=day_iso)
    records_oftheday = data['hourly']['data']
    records.extend( records_oftheday )

# build DF:
allweatherdata = pd.DataFrame.from_records(records, index='time')
allweatherdata.drop(COL2DROP, axis=1, inplace=True, errors='ignore')

allweatherdata.index = pd.to_datetime(allweatherdata.index ,unit='s')

allweatherdata['cloudCover'] = allweatherdata['cloudCover'].fillna( 0 )

allweatherdata.isnull().sum()

allweatherdata.duplicated()

allweatherdata.plot( )

data

"""
Explanation: Debug
End of explanation
"""


