#!/usr/bin/env python3
"""
openweather_app.py
This program uses the OpenWeather API to get current weather 
information and display it in the terminal.

Based on information at https://www.hackster.io/gatoninja236/real-time-weather-with-raspberry-pi-4-ad621f , Real-Time Weather with Raspberry Pi 4
"""

__author__ = "Richard White"
__version__ = "2019-09-09"

import os
import time
import requests
from pprint import pprint

def setup():
    """
    Establishes the settings and base url required 
    for the OpenWeather API. Note that these should
    not be shared in any published version of this
    software!
    """
    settings = {
        'api_key':'your_own_key_goes_here',
        'zip_code':'91103',
        'country_code':'us',
        'temp_unit':'imperial'} #unit can be metric, imperial, or kelvin

    BASE_URL = "http://api.openweathermap.org/data/2.5/weather?appid={0}&zip={1},{2}&units={3}"
    return settings, BASE_URL
    
def display_description():
    """Prints out a description of this program. Useful for
    displays of the project.
    """
    print("""This Python program accesses the 
openweathermap.org API to get weather 
information for the Pasadena area, and 
updates that information once a minute. 
Information is retrieved as a JSON file 
from the website using Python's requests 
library.
    """)
        
def main():
    settings, BASE_URL = setup()
    while True:
        final_url = BASE_URL.format(settings["api_key"],settings["zip_code"],settings["country_code"],settings["temp_unit"])
        os.system('clear')
        display_description()
        print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
            
        # Use a try-except in case the network is unavailable
        try:
            weather_data = requests.get(final_url).json()
            # pprint prints out the json file, 
            # but we only want some of this information
            # pprint(weather_data)
            # prints a selection of the information only
            print("{0} {1} {2}F".format(weather_data['name'], weather_data['weather'][0]['main'], weather_data['main']['temp']))
        except:
            print("Network connection or website unavailable.")

        time.sleep(60) #get new data every minute


if __name__ == "__main__":
    main()

