"""Small helpers shared by the figure scripts: a framed SVG with a title, boxes and arrows.

The colours, font and 700 px width are those of every figure of the site.
"""
from html import escape
from pathlib import Path

import flowcharts

FONT = flowcharts.FONT
SURF, BORDER, INK, INK2, MUTED, GRID = '#fcfcfb', '#dddcd7', '#0b0b0b', '#52514e', '#8a8984', '#eeede9'
BLUE, LIGHT, DARK, ORANGE, SHADE, PALE, GREEN = '#2a78d6', '#a9c9f0', '#1c5cab', '#eb6834', '#f1f0ec', '#e9f1fb', '#2f8f5b'
text = flowcharts.text


def frame(W, H, title, desc, subtitle):
    return [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" '
            f'role="img" font-family="{FONT}">',
            f'<title>{escape(title)}</title>', f'<desc>{escape(desc)}</desc>',
            f'<rect x="0.5" y="0.5" width="{W-1}" height="{H-1}" rx="10" fill="{SURF}" stroke="{BORDER}"/>',
            text(20, 26, title, 14, weight=True), text(20, 46, subtitle, 12, INK2),
            f'<defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" '
            f'orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 Z" fill="{INK2}"/></marker></defs>']


def write(folder, name, parts):
    parts.append('</svg>')
    folder = Path(folder)
    folder.mkdir(parents=True, exist_ok=True)
    (folder / name).write_text('\n'.join(parts) + '\n', encoding='utf-8')
    print(folder / name)


def box(out, x, y, w, h, label, kind='step', size=11.5):
    fill, stroke = {'step': (SURF, INK2), 'state': (PALE, BLUE), 'strong': (BLUE, BLUE),
                    'end': (SHADE, BORDER)}[kind]
    out.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="8" fill="{fill}" stroke="{stroke}" stroke-width="1.4"/>')
    out.extend(flowcharts.lines(x + w / 2, y + h / 2, label, size, 'middle', '#ffffff' if kind == 'strong' else INK))


def arrow(out, d, label=None, lx=0, ly=0, anchor='middle', dash=False):
    extra = ' stroke-dasharray="4 3"' if dash else ''
    out.append(f'<path d="{d}" fill="none" stroke="{INK2}" stroke-width="1.4"{extra} marker-end="url(#ah)"/>')
    if label:
        out.append(text(lx, ly, label, 10.5, INK2, None, anchor))
