"""Vykreslí graf prispevek-k-hladine.svg ze souboru prispevek-k-hladine.json. Vyžaduje ReportLab."""

import json
from pathlib import Path

from reportlab.graphics import renderSVG
from reportlab.graphics.shapes import Drawing, Line, Polygon, Rect, String
from reportlab.lib.colors import HexColor

ROOT = Path(__file__).resolve().parent
INK, MUTED, GRID = [HexColor(v) for v in ("#16383b", "#455c62", "#dce5e2")]
TEAL, RUST = HexColor("#096e73"), HexColor("#a13d25")
WIDTH, HEIGHT = 440, 360


def number(value):
    return f"{value:.1f}".replace(".", ",").replace("-", "−")


def label(d, x, y, value, size=14, color=INK, bold=False, anchor="start"):
    d.add(String(x, y, value, fontName="Helvetica-Bold" if bold else "Helvetica",
                 fontSize=size, fillColor=color, textAnchor=anchor))


def line(d, x1, y1, x2, y2, color=GRID, width=1, dash=None):
    d.add(Line(x1, y1, x2, y2, strokeColor=color, strokeWidth=width, strokeDashArray=dash))


def x(cm):
    return 48 + 8.6 * (cm + 10)


def bar(d, y, low, high, color, mean=None):
    line(d, x(low), y, x(high), y, color, 2.8)
    for tip in (low, high):
        line(d, x(tip), y - 5, x(tip), y + 5, color, 2)
    d.add(Rect(x(low) - 34, y - 7, 30, 14, fillColor=HexColor("#ffffff"), strokeColor=None))
    label(d, x(low) - 6, y - 5, number(low), 13, color, True, "end")
    label(d, x(high) + 6, y - 5, number(high), 13, color, True)
    if mean is not None:
        r = 5
        d.add(Polygon([x(mean), y + r, x(mean) + r, y, x(mean), y - r, x(mean) - r, y],
                      fillColor=color, strokeColor=None))
        label(d, x(mean), y + 9, number(mean), 13, color, True, "middle")


def draw():
    study = json.loads((ROOT / "prispevek-k-hladine.json").read_text(encoding="utf-8"))
    d = Drawing(WIDTH, HEIGHT)
    d.add(Rect(0, 0, WIDTH, HEIGHT, fillColor=HexColor("#ffffff"), strokeColor=None))
    label(d, 14, 336, "Příspěvek k hladině moře 2015–2100 (cm)", 17, bold=True)
    for tick in range(-10, 31, 10):
        line(d, x(tick), 34, x(tick), 300, MUTED if tick == 0 else GRID, 1.4 if tick == 0 else 1)
        label(d, x(tick), 18, str(tick).replace("-", "−"), 13, MUTED, anchor="middle")
    groups = (("Grónsko", TEAL, study["greenland"]["rows"], 304),
              ("Antarktida", RUST, study["antarctica"]["rows"], 166))
    for title, color, rows, top in groups:
        d.add(Rect(10, top - 5, 110, 20, fillColor=HexColor("#ffffff"), strokeColor=None))
        label(d, 14, top, title, 15, color, True)
        for index, row in enumerate(rows):
            y = top - 26 - 54 * index
            d.add(Rect(10, y - 4, 215, 17, fillColor=HexColor("#ffffff"), strokeColor=None))
            label(d, 14, y, f"{row['label']} ({row['scenario']})", 13)
            if "mean" in row:
                bar(d, y - 26, row["mean"] - row["twoSigma"], row["mean"] + row["twoSigma"], color, row["mean"])
            else:
                bar(d, y - 26, row["low"], row["high"], color)
    label(d, x(10), 3, "cm průměrné světové hladiny", 12, MUTED, anchor="middle")
    canvas = renderSVG.SVGCanvas((WIDTH, HEIGHT))
    renderSVG.draw(d, canvas, 0, 0)
    for tag, value in (("title", "Příspěvek Grónska a Antarktidy k hladině moře do roku 2100"),
                       ("desc", "Úsečky ukazují rozpětí výsledků srovnání modelů ISMIP6, kosočtverce průměr souboru pro Grónsko.")):
        canvas.doc.getElementsByTagName(tag)[0].firstChild.data = value
    for node in canvas.doc.getElementsByTagName("text"):
        style = node.getAttribute("style").replace("font-family: Helvetica-Bold;",
                "font-family: Arial, sans-serif; font-weight: bold;").replace(
                "font-family: Helvetica;", "font-family: Arial, sans-serif;")
        node.setAttribute("style", style)
    canvas.save(str(ROOT / "prispevek-k-hladine.svg"))


if __name__ == "__main__":
    draw()
