#!/usr/bin/env python3


import urllib.request
import os
import json
import argparse
import datetime

termcolor_available = True
try:
    from termcolor import colored
except ImportError:
    termcolor_available = False


def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        '--no-request', default=False,
        action='store_true', help='Use previously loaded data'
    )

    parser.add_argument(
        '--location', default='HOME',
        type=str, choices=['HOME', 'WORK'],
        help='Location to get forecasts for'
    )

    parser.add_argument(
        '--compact', default=False,
        action='store_true', help='Compact printing'
    )

    return parser.parse_args()


def get_weather_data(darksky_key, locations, args):
    for location_key, location in locations.items():
        data_path = os.path.join('data', '{}.json'.format(location_key))

        if args.no_request and os.path.isfile(data_path):
            data = json.load(open(data_path))
        else:
            url = 'https://api.darksky.net/forecast/{}/{},{}/?units=si'.format(
                darksky_key, location['latitude'], location['longitude']
            )
            data = json.loads(urllib.request.urlopen(url).read().decode())['hourly']['data']

            json.dump(data, open(data_path, 'w'))

        location['data'] = data


def print_weather_data(locations, args):
    current_date = datetime.datetime.now()
    location = locations[args.location]

    print(chr(27) + '[2J') # clear

    max_intensity = 0.0
    max_probability = 0.0

    datestring = current_date.strftime('%A %-d %B %Y')
    datestring += current_date.strftime(', requested at %H:%M')
    print(datestring)
    print('=' * (len(datestring) if args.compact else 45))

    data = location['data']
    for row in data:
        date = datetime.datetime.utcfromtimestamp(row['time'])
        if date.day != current_date.day:
            continue
        if date.hour < current_date.hour:
            continue

        max_intensity = max(
            max_intensity,
            row['precipIntensity']
        )
        max_probability = max(
            max_probability,
            row['precipProbability']
        )

        time = date.strftime('%I %p')
        precip_probability = round(100 * row['precipProbability'])
        precip_probability_str = '{}%'.format(precip_probability)
        if termcolor_available and precip_probability > 20:
            colour = 'yellow'
            if precip_probability > 40:
                colour = 'red'
            time = colored(time, colour)
            precip_probability_str = colored(precip_probability_str, colour)

        if args.compact:
            print('{}\t{}°C\t{}'.format(
                time,
                round(row['temperature']),
                precip_probability_str,
            ))
        else:
            print('{}\t{}°C\t{:.1f}mm, {}\t{}'.format(
                time,
                round(row['temperature']),
                row['precipIntensity'],
                precip_probability_str,
                row['summary']
            ))

    word = 'precipication '
    if args.compact:
        word = ''
    print('\nMax. {}intensity: {:.1f}mm'.format(
        word, max_intensity
    ))
    print('Max. {}probabiility: {}%'.format(
        word, round(100 * max_probability)
    ))


if __name__ == '__main__':
    os.chdir(
        os.path.dirname(os.path.abspath(__file__))
    )

    config = json.load(open('config.json'))
    darksky_key, locations = config['key'], config['locations']

    args = parse_args()

    if not os.path.exists('data'):
        os.makedirs('data')

    get_weather_data(darksky_key, locations, args)
    print_weather_data(locations, args)
