"""Unlabelled, lettered crops of existing figures for the image-reading items in the final assessment.
Coordinates are pixel positions in the published figures (site/img), chosen on gridded zooms and
checked by eye on the outputs. Writes site/img/q_*.png."""
import pathlib
from PIL import Image, ImageDraw, ImageFont

IMG = pathlib.Path(__file__).resolve().parent.parent / "img"
try:
    FONT = ImageFont.truetype("arialbd.ttf", 30)
except OSError:
    FONT = ImageFont.load_default()
RING = (255, 216, 0)


def label(d, x, y, t, dx=26, dy=-26, r=16):
    d.ellipse([x - r, y - r, x + r, y + r], outline=RING, width=4)
    tx, ty = x + dx, y + dy
    d.rounded_rectangle([tx - 4, ty - 4, tx + 30, ty + 34], 6, fill=(0, 0, 0))
    d.text((tx + 3, ty), t, fill=RING, font=FONT)


def lettered(src, box, scale, pts, out, credit=None):
    im = Image.open(IMG / src).convert("RGB").crop(box)
    im = im.resize((im.width * scale, im.height * scale), Image.LANCZOS if scale == 1 else Image.NEAREST)
    d = ImageDraw.Draw(im)
    for t, x, y, dx, dy in pts:
        label(d, (x - box[0]) * scale, (y - box[1]) * scale, t, dx, dy)
    if credit:  # burn the licence line in below the image
        try:
            small = ImageFont.truetype("arial.ttf", 16)
        except OSError:
            small = ImageFont.load_default()
        lines, cur = [], ""
        for w in credit.split(" "):  # wrap to the image width, measured in the actual font
            trial = (cur + " " + w).strip()
            if small.getlength(trial) > im.width - 12 and cur:
                lines.append(cur); cur = w
            else:
                cur = trial
        lines.append(cur)
        framed = Image.new("RGB", (im.width, im.height + 21 * len(lines) + 8), "white")
        framed.paste(im, (0, 0))
        dd = ImageDraw.Draw(framed)
        for k, ln in enumerate(lines):
            dd.text((im.width - 6, im.height + 5 + 21 * k), ln, fill=(90, 100, 112), font=small, anchor="ra")
        im = framed
    im.save(IMG / out, optimize=True)
    print(out, im.size)


# f9: four 0.75 km tiles of the Berlin VV image (not the published sample boxes), 6x nearest-neighbour
def tiles():
    src = Image.open(IMG / "02_signatures.png").convert("RGB")
    T = 30  # figure px; 5 km scale bar = 200 px, so 30 px = 0.75 km
    spots = [("A", 1520, 600), ("B", 365, 455), ("C", 745, 285), ("D", 868, 425)]  # lake, forest, city, field
    order = ["A", "B", "C", "D"]
    S = 6
    out = Image.new("RGB", (4 * T * S + 3 * 24, T * S + 50), (255, 255, 255))
    d = ImageDraw.Draw(out)
    for i, (t, x, y) in enumerate(spots):
        tile = src.crop((x, y, x + T, y + T)).resize((T * S, T * S), Image.NEAREST)
        ox = i * (T * S + 24)
        out.paste(tile, (ox, 50))
        d.text((ox + 4, 6), t, fill=(0, 0, 0), font=FONT)
    out.save(IMG / "q_tiles.png", optimize=True)
    print("q_tiles.png", out.size, [s[0] for s in spots], order)


tiles()
# f11: lower right of Himalaya panel D (descending, terrain-corrected); A = smeared bright band, B = black patch
lettered("04_geometry.png", (1300, 1100, 1705, 1535), 2, [("A", 1462, 1197, 26, -60), ("B", 1486, 1506, 30, -66)], "q_geometry.png")
# f15: change composite (red = earlier only, cyan = later only); A cyan along a quay, B dark water,
#      C red blob on the water, D bright on both dates (white)
lettered("05_change.png", (1458, 225, 1758, 405), 3,
         [("C", 1595, 290, 22, -60), ("A", 1621, 349, 26, 10), ("D", 1733, 236, -60, 0), ("B", 1530, 296, -24, -64)], "q_change.png")
# f20: ICEYE half of the Tollerort close-up; radar to the east-north-east (right); D = laid-over crane
#      (A stack block, B open water, C quay). The credit strip is added below the crop.
lettered("hero_tollerort.png", (900, 32, 1660, 795), 1,  # crop stays above the credit strip
         [("D", 1400, 215, 22, -58), ("A", 1100, 352, 22, -58), ("B", 1550, 282, 22, 12), ("C", 1322, 432, -60, -10)], "q_cranes.png",
         credit="ICEYE SAR Open Dataset (c) ICEYE, CC BY 4.0, modified by David Reid. Dashed line (c) OpenStreetMap contributors, ODbL.")
