#!/usr/bin/env python3
#
# This file is part of vaisalad.
#
# vaisalad is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# vaisalad is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with vaisalad.  If not, see <http://www.gnu.org/licenses/>.

"""Commandline client for querying the latest measurement from vaisalad"""

import sys
import Pyro4

DAEMON_URI = 'PYRO:vaisala_daemon@localhost:9001'

def print_last_measurement():
    """Prints the latest weather data in human-readable form"""
    latest = None
    error = None
    try:
        with Pyro4.Proxy(DAEMON_URI) as vaisala:
            latest = vaisala.last_measurement()
            error = vaisala.last_error()
    except Pyro4.errors.CommunicationError:
        print('Failed to query Vaisala daemon')
        return 1

    if latest is not None:
        print('Data received {}:'.format(latest['date']))
        print(u'Wind Direction: {} \u00B0'.format(latest['wind_direction']))
        print(u'    Wind Speed: {} km/h'.format(latest['wind_speed']))
        print(u'   Temperature: {} \u2103'.format(latest['temperature']))
        print(u' Rel. Humidity: {} %'.format(latest['relative_humidity']))
        print(u'      Pressure: {} hPa'.format(latest['pressure']))
        print(u'   Accum. Rain: {} mm'.format(latest['accumulated_rain']))
        print(u'  Heater Temp.: {} \u2103'.format(latest['heater_temperature']))
        print(u'Heater Voltage: {} V'.format(latest['heater_voltage']))
        print()
    else:
        print('No data available')

    if error[0] is not None:
        print('Last error was at {}'.format(error[0]))
        print(error[1])
    return 0
if __name__ == '__main__':
    sys.exit(print_last_measurement())
