"""
Module/Script to read the weather.json file.

The main function in this module will allow you to access the most recent weather report,
given a specified time. The script provides a nice user interface to this function, but
it is limited to visibility, wind, and temperature.

Author: Walker M. White (wmw2)
Date:   September 24, 2018
"""
import introcs          # To read the JSON file
import datetime         # To handle time


def str_to_time(value):
    """
    Returns: The datetime object corresponding to the given ISO time format.
    
    There is an ISO specification for how to represent time as a string.  However,
    turning it into a datetime object is a bit arcane.  So we separate this off as
    its own function.
    
    Parameter value: The time value as an ISO string
    Precondition: value is a string containing a valid ISO time
    """
    import dateutil.parser  # To convert strings into dates
    localtime = dateutil.parser.parse(value)
    utctime   = localtime.astimezone(datetime.timezone.utc)
    return utctime


def get_report(file,timestamp):
    """
    Returns: The most recent weather report BEFORE timestamp
    
    If there is no weather report before timestamp, this function returns None.
    
    Parameter file: The json file with the weather information
    Precondition: file is a string containing a valid JSON file name.
    
    Parameter timestamp: The time for the weather report
    Precondition: timestamp is a datetime object
    """
    # Read the file and load into a dictionary
    reports = introcs.read_json(file)
    
    # The closest report BEFORE timestamp
    closest = None
    result  = None
    
    # Loop through the keys, which are strings as timestamps
    for key in reports:
        # Turn it into a date
        thetime = str_to_time(key)
        # If it is before date, but the closest so far, remember it
        if thetime < timestamp:
            if closest is None or closest < thetime:
                closest = thetime
                result  = reports[key]
    
    return result


def prompt_user(file):
    """
    Prompts the user for input to get the weather information.
    
    This function is used by the script code to run the script.
    
    Parameter file: The json file with the weather information
    Precondition: file is a string containing a valid JSON file name.
    """
    print('For weather information, enter a date and hour in UTC time.')
    month = int(input('Month: '))
    day   = int(input('Day: '))
    hour  = int(input('Hour: '))
    
    choice = input('[V]isibility, [T]emperature, or [W]ind: ')
    if not choice in ['V','T','W']:
        print('That is not a valid option.')
        return
    
    thetime = datetime.datetime(2017,int(month),int(day),int(hour),tzinfo=datetime.timezone.utc)
    report  = get_report(file,thetime)
    
    if choice == 'V':
        print('Visibility is '+str(report['visibility']['prevailing'])+' '+report['visibility']['units']+'.')
    elif choice == 'T':
        print('Temperature is '+str(report['temperature']['value'])+' '+report['temperature']['units']+'.')
    elif choice == 'W':
        print('Wind is '+str(report['wind']['speed'])+' '+report['wind']['units']+'.')
    else:
        print('The script encountered an unknown error.')


if __name__ == '__main__':
    prompt_user('weather.json')
