#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import os
import requests
import time
from ConfigParser import SafeConfigParser

import sys
reload(sys)
sys.setdefaultencoding('utf8')


def is_weather_doc_valid(config):
    doc = config['doc']

    if not os.path.exists(doc):
        return False

    mtime = os.path.getmtime(doc)
    now = time.time()
    if int(now) - int(mtime) >= 3600:
        return False

    return True


def fetch_weather_doc(config):
    url = config['url']
    doc = config['doc']

    r = requests.get(url)

    if os.path.exists(doc):
        os.unlink(doc)

    with open(doc, 'w') as f:
        f.write(r.content)


def get_weather_data(config):
    doc = config['doc']

    with open(doc) as f:
        raw = json.load(f)
    return raw['current_observation']


def plot_weather(config, data):
    icons = config['icons']
    icon_type = config['icon_type']
    icon_url = data['icon_url']
    temp = data['temp_c']

    icon = icon_url.split('/')[-1].replace('gif', icon_type)
    print "%s/%s" % (icons, icon)
    print "%.1f °C" % (temp)


def parse_config():
    config_file = os.path.join(os.environ['HOME'],
                               '.config/tint2/weather/wunderground.cfg')

    parser = SafeConfigParser()
    parser.read(config_file)

    api_key = parser.get('wunderground', 'api_key')
    station = parser.get('wunderground', 'station')
    icons = parser.get('wunderground', 'icons')
    icon_type = parser.get('wunderground', 'icon_type')

    doc = '/tmp/wunderground-%s-%s.json' % (api_key, station)
    url = 'http://api.wunderground.com/api/%s/conditions/q/pws:%s.json' % \
          (api_key, station)

    config = {'api_key': api_key,
              'icon_type': icon_type,
              'icons': icons,
              'doc': doc,
              'station': station,
              'url': url}

    return config


def run():
    config = parse_config()
    if not is_weather_doc_valid(config):
        fetch_weather_doc(config)
    data = get_weather_data(config)
    plot_weather(config, data)


if __name__ == '__main__':
    run()
