#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (C) 2012-2019 British Crown (Met Office) & Contributors - GNU V3+.
# This is illustrative code developed for tutorial purposes, it is not
# intended for scientific use and is not guarantied to be accurate or correct.
# -----------------------------------------------------------------------------
"""
Usage:
    get-observations

Environment Variables:
    SITE_ID: The four digit DataPoint site code identifying the weather station
        we are to fetch results for.
    API_KEY: The DataPoint API key, required for getting live weather data.
        If un-specified then get-observations will fall back to archive data
        from the suite directory.

"""

from datetime import datetime
import json
import os
import urllib2


BASE_URL = ('http://datapoint.metoffice.gov.uk/public/data/'
            'val/wxobs/all/json/{site_id}'
            '?res=hourly&time={time}&key={api_key}')

# Compass bearings for ordinate directions.
# NOTE: We measure direction by where the winds have come from!
ORDINATES = {
    'N': '180',
    'NNE': '202.5',
    'NE': '225',
    'ENE': '247.5',
    'E': '270',
    'ESE': '292.9',
    'SE': '315',
    'SSE': '337.5',
    'S': '0',
    'SSW': '22.5',
    'SW': '45',
    'WSW': '67.5',
    'W': '90',
    'WNW': '112.5',
    'NW': '135',
    'NNW': '157.5'
}


def get_datapoint_data(site_id, time, api_key):
    """Get weather data from the DataPoint service."""
    # The URL required to get the data.
    time = datetime.strptime(time, '%Y%m%dT%H%MZ').strftime('%Y-%m-%dT%H:%MZ')
    url = BASE_URL.format(time=time, site_id=site_id,
                          api_key=api_key)
    # Get the data and parse it as JSON.
    print 'Opening URL: %s' % url
    return json.loads(urllib2.urlopen(url).read())['SiteRep']['DV']['Location']


def get_archived_data(site_id, time):
    """Return archived weather data from the suite directory."""
    print [os.environ['CYLC_SUITE_DEF_PATH'], 'data', time, site_id + '.json']
    path = os.path.join(
        os.environ['CYLC_SUITE_DEF_PATH'], 'data', time, site_id + '.json')
    print 'Opening File: %s' % path
    return json.load(file(path))['SiteRep']['DV']['Location']


def extract_observations(data):
    """Extract the relevant observations from the weather data."""
    return [data['lon'],
            data['lat'],
            ORDINATES[data['Period']['Rep']['D']],
            data['Period']['Rep']['S']]


def main(site_id, api_key=None):
    cycle_point = os.environ['CYLC_TASK_CYCLE_POINT']

    if api_key:
        print 'Attempting to get weather data from DataPoint...'
        data = get_datapoint_data(site_id, cycle_point, api_key)
    else:
        print 'No API key provided, falling back to archived data'
        data = get_archived_data(site_id, cycle_point)

    obs = extract_observations(data)

    # Write observations.
    with open('wind.csv', 'w+') as data_file:
        data_file.write(', '.join(obs))


if __name__ == '__main__':
    main(os.environ['SITE_ID'],
         os.environ.get('API_KEY'))
