"""Vykreslí graf sila-proudeni.svg ze souboru sila-proudeni.json. Vyžaduje ReportLab."""

import json
from pathlib import Path

from reportlab.graphics import renderSVG
from reportlab.graphics.shapes import Circle, 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, 330


def number(value):
    return f"{value:.1f}".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 diamond(d, x, y, color, r=5):
    d.add(Polygon([x, y + r, x + r, y, x, y - r, x - r, y], fillColor=color, strokeColor=None))


def x(sv):
    return 140 + 13 * sv


def draw():
    study = json.loads((ROOT / "sila-proudeni.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, 306, "Síla proudění na 26° s. š. (Sv)", 17, bold=True)
    for tick in range(0, 21, 5):
        line(d, x(tick), 34, x(tick), 262)
        label(d, x(tick), 18, str(tick), 13, MUTED, anchor="middle")
    threshold = study["collapseThreshold"]["value"]
    line(d, x(threshold), 34, x(threshold), 262, MUTED, 1.4, [4, 3])
    label(d, x(threshold) + 5, 40, "Hranice zhroucení 6 Sv", 12, MUTED)
    label(d, 14, 272, "Měření RAPID", 14, TEAL, True)
    for index, row in enumerate(study["measurements"]["rows"]):
        y = 248 - 26 * index
        label(d, 14, y - 5, row["period"], 13)
        d.add(Circle(x(row["mean"]), y, 5, fillColor=TEAL, strokeColor=None))
        label(d, x(row["mean"]) + 10, y - 5, number(row["mean"]), 13, TEAL, True)
    label(d, 14, 156, "Projekce 2091–2100", 14, RUST, True)
    base = study["projections"]["referenceMean"]
    for index, row in enumerate(study["projections"]["rows"]):
        y = 124 - 48 * index
        label(d, 14, y + 2, row["label"], 13)
        label(d, 14, y - 13, row["scenario"], 12, MUTED)
        low, high = base - row["declineHigh"], base - row["declineLow"]
        line(d, x(low), y, x(high), y, RUST, 2.8)
        for tip in (low, high):
            line(d, x(tip), y - 5, x(tip), y + 5, RUST, 2)
        best = base - row["decline"]
        diamond(d, x(best), y, RUST)
        label(d, x(best), y + 10, number(best), 13, RUST, True, "middle")
    label(d, x(10), 3, "milion m³ vody za sekundu", 12, MUTED, anchor="middle")
    canvas = renderSVG.SVGCanvas((WIDTH, HEIGHT))
    renderSVG.draw(d, canvas, 0, 0)
    for tag, value in (("title", "Síla atlantické cirkulace: měření a projekce"),
                       ("desc", "Kruhy ukazují průměry měření RAPID, kosočtverce s úsečkami projekce Weijera a kol. pro roky 2091–2100.")):
        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 / "sila-proudeni.svg"))


if __name__ == "__main__":
    draw()
