"""Make the figures for the scipython.com dotted maps blog post, in a
light and a dark version to match the site's pages.

Usage: python dotted_map_for_web_figs.py

Draws the maps with the dotted-map package, and writes SVG images to
output/ and PNG versions (at twice the size) made with rsvg-convert.
"""

import re
import subprocess
from pathlib import Path

import numpy as np

from dotted_map import DottedMap

OUT = Path("output")

# Colours to match the site's light and dark pages.
THEMES = {
    "light": {"page": "#fbfbfc", "purple": "#4b2a8e", "red": "#d44627",
              "green": "#009246", "land": "#3a3f4b", "sea": "#e3e6ec",
              "accent": "#f0532f", "grey": "#8e98aa",
              "tropics": (38, 166, 154), "poles": (63, 81, 181)},
    "dark": {"page": "#2a2b30", "purple": "#a993ec", "red": "#ef6b4d",
             "green": "#4cc38a", "land": "#d9dde6", "sea": "#3b3d45",
             "accent": "#ff7a57", "grey": "#767d8e",
             "tropics": (77, 208, 196), "poles": (140, 158, 255)},
}


def write(name, svg, theme, suffix):
    """Write svg to output/name.svg and a PNG version on the page colour."""
    path = OUT / f"{name}{suffix}.svg"
    path.write_text(svg)
    subprocess.run(["rsvg-convert", "-z", "2", "-b", theme["page"], str(path),
                    "-o", str(path.with_suffix(".png"))], check=True)


def side_by_side(svgs, gap=24):
    """Return SVG documents of equal height placed side by side as one."""
    x, parts, height = 0, [], None
    for svg in svgs:
        w, height = map(int, re.search(r'width="(\d+)" height="(\d+)"',
                                       svg).groups())
        parts.append(svg.replace("<svg ", f'<svg x="{x}" ', 1))
        x += w + gap
    return (f'<svg xmlns="http://www.w3.org/2000/svg" '
            f'viewBox="0 0 {x - gap} {height}" width="{x - gap}" '
            f'height="{height}">\n' + "\n".join(parts) + "\n</svg>\n")


def with_height(height, **kwargs):
    """Return a DottedMap whose image is (very nearly) height px high."""
    probe = DottedMap(samples=1, **kwargs)
    aspect = (probe.xmax - probe.xmin) / (probe.ymax - probe.ymin)
    m = probe.margin
    return DottedMap(width=round((height - 2 * m) * aspect + 2 * m), **kwargs)


def by_latitude(c0, c1, shades=8):
    """Return a colour function shading from c0 at the equator to c1 at
    70 degrees of latitude and beyond, in a given number of shades."""
    c0, c1 = np.array(c0), np.array(c1)

    def colour(lon, lat):
        t = np.round(np.clip(np.abs(lat) / 70, 0, 1) * (shades - 1))
        rgb = (c0 + (c1 - c0) * t[:, None] / (shades - 1)).astype(int)
        return [f"#{r:02x}{g:02x}{b:02x}" for r, g, b in rgb]
    return colour


# The maps are independent of the theme: lay them out once.
uk = (-11, 2, 49.8, 61)
british_isles = DottedMap(uk, width=600, spacing=8)
# Plate carree and Lambert azimuthal equal-area, on the same square lattice.
projections = [with_height(520, extent=uk, projection=proj, spacing=10,
                           grid="square") for proj in ("+proj=eqc", None)]
# The Aegean Sea: the land sampled only at the centre of each cell, and at
# 5 x 5 points within it.
aegean = dict(extent=(19.5, 28.5, 35.0, 41.5), width=420, spacing=8)
aegean_point = DottedMap(samples=1, **aegean)
aegean_area = DottedMap(**aegean)
africa = DottedMap((-20, 52, -36, 38), width=600, spacing=10)
italy = DottedMap(region="Italy", land="Italy", width=400, spacing=8)
world = DottedMap((-180, 180, -57, 84), width=1200, spacing=8)
globe = DottedMap(projection="+proj=ortho +lon_0=-25 +lat_0=28", width=600,
                  spacing=8)
europe = DottedMap(projection="EPSG:3035", width=700, spacing=6,
                   bounds=(2.55e6, 1.35e6, 6.55e6, 5.5e6))

places = {"London": (-0.13, 51.51), "New York": (-74.0, 40.71),
          "San Francisco": (-122.42, 37.77), "Sao Paulo": (-46.63, -23.55),
          "Nairobi": (36.82, -1.29), "Singapore": (103.82, 1.35),
          "Sydney": (151.21, -33.87), "Tokyo": (139.69, 35.69)}
routes = [("San Francisco", "New York"), ("New York", "London"),
          ("New York", "Sao Paulo"), ("London", "Nairobi"),
          ("London", "Singapore"), ("Singapore", "Sydney"),
          ("Singapore", "Tokyo")]

OUT.mkdir(exist_ok=True)
for mode, t in THEMES.items():
    suffix = "" if mode == "light" else "-dark"
    write("british-isles", british_isles.svg(colour=t["purple"]), t, suffix)
    write("projections", side_by_side([m.svg(colour=t["purple"])
                                       for m in projections]), t, suffix)
    write("coastlines", side_by_side([
        aegean_point.svg(colour=t["purple"]),
        aegean_area.svg(colour=t["purple"]),
        aegean_area.svg(colour=t["purple"], halftone=True)]), t, suffix)
    write("africa-hexagons", africa.svg(colour=t["red"], shape="hexagon",
                                        size=0.8), t, suffix)
    write("italy", italy.svg(colour=t["green"], shape="hexagon"), t, suffix)

    world.pins, world.arcs = [], []
    pins = {name: world.add_pin(*lonlat, colour=t["accent"])
            for name, lonlat in places.items()}
    for a, b in routes:
        world.add_arc(pins[a], pins[b], bend=0.25)
    write("world-routes", world.svg(colour=t["land"], sea=t["sea"],
                                    size=0.62), t, suffix)

    write("globe", globe.svg(colour=by_latitude(t["tropics"], t["poles"]),
                             sea=t["sea"], size=0.66), t, suffix)
    write("europe-uk", europe.svg(colour=t["grey"], halftone=True,
                                  highlight={"GBR": t["accent"]}), t, suffix)
    print(f"{mode} figures written to {OUT}/")
