#!/usr/bin/python
# -*- coding=utf-8 -*-

import sys
import getopt
import pymetar
from urllib2 import URLError

DEFAULT = 'KBOS'

if __name__ == '__main__':
    opts, args = getopt.getopt(sys.argv[1:], 'vi')

    verbose = False
    imperial = False
    for opt, arg in opts:
        if opt == '-v':
            verbose = True
        if opt == '-i':
            imperial = True

    try:
        station = args[0]
    except IndexError:
        station = DEFAULT

    try:
        fetcher = pymetar.ReportFetcher(station)
        parser = pymetar.ReportParser()
        report = parser.ParseReport(fetcher.FetchReport())
        if imperial:
            getTemperature = report.getTemperatureFahrenheit
            getDewPoint = report.getDewPointFahrenheit
            getVisibility = report.getVisibilityMiles
            visibilityUnits = 'mi'
        else:
            getTemperature = report.getTemperatureCelsius
            getDewPoint = report.getDewPointCelsius
            getVisibility = report.getVisibilityKilometers
            visibilityUnits = 'km'
    except URLError, e:
        print 'Error fetching METAR: %s' % e.args[0][1]
        sys.exit(1)

    if verbose:
        head = '%s; %s' % (report.getStationCity(), report.getISOTime())
        print head; print '=' * len(head)

        obs = []
        obs.append(('Conditions', report.getWeather()))
        obs.append(('Temperature', getTemperature()))
        obs.append(('Wind', '%s %s m/s' % (report.getWindCompass(), report.getWindSpeed())))
        obs.append(('Visibility', '%s %s' % (getVisibility(), visibilityUnits)))
        obs.append(('Dew Point', '%s' % getDewPoint()))
        obs.append(('Humidity', '%s%%' % report.getHumidity()))

        width = max([len(o[0]) for o in obs]) + 2
        for m, v in obs:
            print '%*s: %s' % (width, m, v)
    else:
        print report.getWeather(), '%s°' % getTemperature()
