#! /usr/bin/env python3

import urllib
import json
#from subprocess import call
import sys
import time
import os.path
import urllib.parse
import urllib.request
#import time

woeid=sys.argv[1]
path="/home/kuba/.conky/weather/last-"+woeid+".json"
#Try to download new data; overwrite existing file
def fetch_data():
    base_url = "https://query.yahooapis.com/v1/public/yql"
    sel_url = "?q=select%20location,wind,atmosphere,astronomy,item%20from%20weather.forecast"
    where_url = "%20where%20u='c'%20and%20woeid%20=%20" + woeid
    format_url = "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
    yql_url = base_url + sel_url + where_url + format_url
    try:
        result = urllib.request.urlopen(yql_url).read()
        data = json.loads(result)
        ch = data['query']['results']['channel']

        timestamp = str(round(time.time()))
        parsed_data = {}#Don't save everything
        parsed_data['timestamp'] = timestamp
        for s in ['location', 'wind', 'atmosphere', 'astronomy']:
            parsed_data.update({s : ch[s]})
        for s in ['lat','long','condition','forecast']:
            parsed_data.update({s : ch['item'][s]})
        with open(path, 'w') as outfile:
            json.dump(parsed_data, outfile)
    except urllib.error.URLError:
        pass
    return

def print_output(data):
    timestamp = int(data['timestamp'])

    city = data['location']['city']
    country = data['location']['country']

    current_condition = data['condition']['text']
    current_code      = data['condition']['code']
    current_temp      = data['condition']['temp']
    #weather_date      = data['condition']['date']

    speed_unit = "km/h"
    speed = data['wind']['speed']

    humidity =  data['atmosphere']['humidity']

    forecast = []
    for forec in data['forecast']:
	    forecast.append((forec['day'], forec['low'], forec['high'] , forec['code']))


    print ("${font Open Sans:size=15:style=Light}%s, %s " % (city, country), end = '')
    print ("${font :size=6}${alignr}${color7}Updated: ${color white}%s ${color7}Fetched: ${color white}%s" % (time.strftime("%I:%M"), time.strftime("%m/%d %H:%M", time.gmtime(timestamp))))
    print ("${color7}${hr}${color}")
    print ("${voffset -5}${font Open Sans:size=60:style=Light}%s°${font}" %(current_temp))
    print ("${offset 250}${voffset -65}%s" %(current_condition))
    print ("${image ~/.conky/.conky-google-now/%s.png -p 180,45 -s 60x60}" %(current_code))
    print ("${image ~/.conky/.conky-google-now/wind.png -p 245,62 -s 15x15}${goto 35}${offset 250}${voffset -12}%s %s" %(speed, speed_unit), end = '')
    print ("${goto 400}%s ${goto 530} %s" %(forecast[0][0].upper(), forecast[1][0].upper()))
    print ("${image ~/.conky/.conky-google-now/humidity.png -p 245,81 -s 15x15}${goto 35}${offset 250}%s %s" %(humidity,"%"), end = '')
    print ("${goto 400}%s°${color6}%s°${color}${goto 530}%s°${color6}%s°${color}${voffset 15}" %(forecast[0][2], forecast[0][1], forecast[1][2], forecast[1][1]))
    print ("${image ~/.conky/.conky-google-now/%s.png -p 440,65 -s 30x30}${image ~/.conky/.conky-google-now/%s.png -p 570,65 -s 30x30}${voffset -10}" %(forecast[0][3], forecast[1][3]))
    return

#Open existing file and check if it's not too old
if not (os.path.isfile(path)):
    fetch_data()
with open(path) as infile:
    data = json.load(infile)
ts = int(data['timestamp'])
now = round(time.time())
if (ts + 3600 < now):
    fetch_data()
    ts = now
print_output(data)
