#!/usr/bin/python3

# PROBLEM:
#  * http://bom.gov.au is 90s style and very hard to use.
#    It also requires js, and is not SSL so COMPLETELY UNSAFE.
#  * http://m.bom.gov.au provided a GOOD option with two simple pages:
#      1. a full-screen rain radar for the last 15 minutes.
#         This tells me the heavy rainstorm is just starting, or just finishing.
#         This in turn tells me whether to leave now or wait 15 minutes.
#      2. For my station only (Melbourne CBD),
#          * min/max temp, rain chance forecasts for the rest of today
#          * severe weather warnings, in big letters, with a solid yellow background.
#  * m.bom.gov.au was shut down and replaced by an "app" that requires ios or dalvik.
#  * the backend data is now commercialized, so open source alternative interfaces to this data CANNOT EXIST ANYMORE.
#    i.e. bom.gov.au is trying to buck the govhack trend and make Australian weather MORE like American weather -- expensive and exclusive.
#
# So let's try to solve the most immediate problem: merge the rain GIF overlay onto the static map PNGs, as the javascript does.
# Then render that into a static png or webm, and view it.

import pwd
import os
import tempfile
import pathlib
import datetime
import subprocess

underlays = ('background', 'locations', 'range', 'topography')

with tempfile.TemporaryDirectory() as tempdir_str:
    tempdir_path = pathlib.Path(tempdir_str)
    now = datetime.datetime.utcnow()  # NOTE: TZ=UTC
    # Truncate to start of hour to kludge over with propagation delays on the bom.gov.au servers
    # This means the data will be up to 1h delayed, so FIXME.
    # now = now.replace(minute=0)
    subprocess.call([
        'wget', '-nv', '-P', tempdir_path,
        '--',
        # Try to get a rain image for every minute in the last hour.
        # 1 in every 6 will work.  For now, just ignore that some fail.
        # FIXME: this is VERY VERY VERY slow to download.
        *[then.strftime('http://www.bom.gov.au/radar/IDR023.T.%Y%m%d%H%M.png')
          for i in range(60)
          for then in [(now - datetime.timedelta(minutes=i))]
          if then.minute % 6 == 0],
        # The underlay images (NOTE: hardcode station to MEL (IDR023) for now).
        *[f'http://www.bom.gov.au/products/radar_transparencies/IDR023.{u}.png'
          for u in underlays]])
    # Merge the underlays and overlays into combined images.
    # We have to do this a bit at a time, because reasons.
    # For now just to the map overlay and skip land/sea &c
    for overlay_path in tempdir_path.glob('*.T.*png'):
        subprocess.check_call(['gm', 'composite', overlay_path,                        tempdir_path / 'IDR023.locations.png',   overlay_path.with_suffix(f'.1.png')])
        subprocess.check_call(['gm', 'composite', overlay_path.with_suffix(f'.1.png'), tempdir_path / 'IDR023.range.png',       overlay_path.with_suffix(f'.2.png')])
        subprocess.check_call(['gm', 'composite', overlay_path.with_suffix(f'.2.png'), tempdir_path / 'IDR023.topography.png',  overlay_path.with_suffix(f'.3.png')])
        subprocess.check_call(['gm', 'composite', overlay_path.with_suffix(f'.3.png'), tempdir_path / 'IDR023.background.png',  overlay_path.with_suffix(f'.4.png')])

    # Convert to an animated gif.
    # FIXME: currently bugged -- it's not wiping the transparent cells between frames.
    #        When I add in the all-opaque underlay that should fix it.
    subprocess.check_call(['gm', 'convert',
                           '-delay', '100',  # 1s per frame
                           '-loop', '0',    # loop forever
                           *tempdir_path.glob('*.T.*.4.png'),
                           tempdir_path / 'final.gif'])

    if pwd.getpwuid(os.geteuid()).pw_name != 'twb':
        # Normal people -- just open a browser or whatever.
        subprocess.check_call(['xdg-open', tempdir_path / 'final.gif'])
    else:
        # Author version -- I'm too lazy to fix my .desktop associations to distinguish "animated gifs" (mpv) from "gifs" (xzgv).
        subprocess.check_call(['mpv', '-loop', tempdir_path / 'final.gif'])
