"""Draws the four ways a line lays its ink down, and a table ruled with them.

The Python twin of the `write_dotted_rules` example in Rust. A stroke states a width
and a colour, and now also a line style: the dashes and gaps it follows, the shape at
its two ends, and the shape where two of its segments meet. A table's rules and a
cell's border carry one, so a statement is ruled with hairline dots rather than with
solid lines.

Both sets of words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn.

Usage: python examples/write_dotted_rules.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_dotted_rules.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf


@dataclass(frozen=True)
class Words:
    """Every word the page draws, in one language."""

    # The page's title.
    title: str
    # What the page is about.
    lead: str
    # The heading over the four sample lines.
    patterns: str
    # What each of the four sample lines is called.
    pattern_names: tuple[str, str, str, str]
    # The heading over the three ends.
    ends: str
    # What each of the three ends is called.
    end_names: tuple[str, str, str]
    # The heading over the three corners.
    corners: str
    # What each of the three corners is called.
    corner_names: tuple[str, str, str]
    # The heading over the ruled table.
    ruled: str
    # The two column headings of that table.
    columns: tuple[str, str]
    # What the four rows of that table are called.
    rows: tuple[str, str, str, str]
    # The label on the total row.
    total: str
    # What a dash of no length needs to be seen.
    caveat: str


# The page in English.
ENGLISH = Words(
    title="Lines that are not solid",
    lead=(
        "A stroke says how thick it is and what colour it is drawn in, and it may also "
        "say how the ink is laid down: the dashes and gaps it follows, the shape at "
        "its two ends, and the shape where two of its segments meet. Nothing below is "
        "drawn twice — each line is one stroke, told what to look like."
    ),
    patterns="Four patterns",
    pattern_names=(
        "Solid, which is what a stroke does when it is told nothing",
        "Dashes of four points, gaps of two",
        "Dashes and gaps of the same three points",
        "Dots, which are dashes of no length at all",
    ),
    ends="Three ends",
    end_names=("Squared off", "Rounded", "Squared off past the end"),
    corners="Three corners",
    corner_names=("Pointed", "Rounded", "Cut off"),
    ruled="A statement ruled with dots",
    columns=("Description", "Amount"),
    rows=(
        "Drawing office, February",
        "Plates and proofs",
        "Delivery, two crates",
        "Storage, one month",
    ),
    total="Total",
    caveat=(
        "A dot is a dash of no length, so it puts ink down only under a rounded end: "
        "told to square its ends off, the same pattern draws nothing at all. That is "
        "why the dotted lines here ask for both."
    ),
)

# The page in French.
FRENCH = Words(
    title="Des traits qui ne sont pas pleins",
    lead=(
        ("Un trait indique son épaisseur et sa couleur, et peut aussi préciser comment"
         " l’encre est posée : les tirets et les blancs qu’il suit, la forme de ses "
         "deux bouts, et celle de l’angle où deux de ses segments se rejoignent. Rien "
         "ci-dessous n’est dessiné deux fois : chaque ligne est un seul trait, dont on"
         " a seulement réglé l’aspect.")
    ),
    patterns="Quatre motifs",
    pattern_names=(
        "Plein, soit un trait laissé sans consigne",
        "Tirets de quatre points, blancs de deux",
        "Tirets et blancs de trois points chacun",
        "Points, c’est-à-dire des tirets de longueur nulle",
    ),
    ends="Trois bouts",
    end_names=("Coupé net", "Arrondi", "Coupé net au-delà du bout"),
    corners="Trois angles",
    corner_names=("En pointe", "Arrondi", "Abattu"),
    ruled="Un relevé réglé en pointillé",
    columns=("Désignation", "Montant"),
    rows=(
        "Bureau d’études, février",
        "Plaques et épreuves",
        "Livraison, deux caisses",
        "Entreposage, un mois",
    ),
    total="Total",
    caveat=(
        ("Un point est un tiret sans longueur : il ne dépose d’encre que sous un bout "
         "arrondi. Avec des bouts coupés net, le même motif ne dessine rien du tout. "
         "C’est pourquoi les pointillés de cette page associent ce motif à des bouts "
         "arrondis.")
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Lijnen die niet doorgetrokken zijn",
    lead=(
        "Een lijn zegt hoe dik ze is en in welke kleur ze getekend wordt, en ze kan "
        "ook zeggen hoe de inkt wordt neergelegd: de streepjes en tussenruimten die "
        "ze volgt, de vorm van haar twee uiteinden en de vorm waar twee segmenten "
        "elkaar raken. Niets hieronder is twee keer getekend: elke lijn is één lijn "
        "die te horen krijgt hoe ze eruit moet zien."
    ),
    patterns="Vier patronen",
    pattern_names=(
        "Doorgetrokken, wat een lijn zonder instructie doet",
        "Streepjes van vier punten, tussenruimten van twee",
        "Streepjes en tussenruimten van dezelfde drie punten",
        "Puntjes: streepjes zonder lengte",
    ),
    ends="Drie uiteinden",
    end_names=("Recht afgesneden", "Afgerond", "Recht, voorbij het einde"),
    corners="Drie hoeken",
    corner_names=("Puntig", "Afgerond", "Afgeschuind"),
    ruled="Een afschrift met stippellijnen",
    columns=("Omschrijving", "Bedrag"),
    rows=(
        "Tekenkamer, februari",
        "Platen en proeven",
        "Levering, twee kratten",
        "Opslag, één maand",
    ),
    total="Totaal",
    caveat=(
        "Een puntje is een streepje zonder lengte, dus legt het alleen inkt neer "
        "onder een afgerond uiteinde: met rechte uiteinden tekent hetzelfde patroon "
        "helemaal niets. Daarom vragen de stippellijnen hier om allebei."
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Linhas que não são contínuas",
    lead=(
        "Uma linha diz a sua espessura e a cor com que é desenhada, e pode também "
        "dizer como se põe a tinta: os traços e intervalos que segue, a forma das "
        "duas pontas e a forma onde se juntam dois dos seus segmentos. Nada abaixo é "
        "desenhado duas vezes: cada linha é a mesma a que se diz que aspeto ter."
    ),
    patterns="Quatro padrões",
    pattern_names=(
        "Contínuo, o que uma linha faz quando não se lhe diz nada",
        "Traços de quatro pontos, intervalos de dois",
        "Traços e intervalos dos mesmos três pontos",
        "Pontos, que são traços de comprimento nulo",
    ),
    ends="Três pontas",
    end_names=("Retas", "Arredondadas", "Retas para lá do fim"),
    corners="Três cantos",
    corner_names=("Em bico", "Arredondados", "Cortados"),
    ruled="Um extrato riscado a pontos",
    columns=("Descrição", "Montante"),
    rows=(
        "Gabinete técnico, fevereiro",
        "Chapas e provas",
        "Entrega, duas caixas",
        "Armazenagem, um mês",
    ),
    total="Total",
    caveat=(
        "Um ponto é um traço de comprimento nulo, por isso só põe tinta sob uma ponta "
        "arredondada: com pontas retas, o mesmo padrão não desenha nada. É por isso "
        "que as linhas ponteadas aqui pedem as duas coisas."
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Linee che non sono continue",
    lead=(
        "Un tratto dice quanto è spesso e di che colore è disegnato, e può dire anche "
        "come si stende l’inchiostro: i trattini e gli spazi che segue, la forma "
        "delle due estremità e la forma dove si uniscono due dei suoi segmenti. "
        "Niente qui sotto è disegnato due volte: ogni linea è un tratto a cui si dice "
        "che aspetto avere."
    ),
    patterns="Quattro motivi",
    pattern_names=(
        "Continuo, ciò che fa un tratto quando non gli si dice nulla",
        "Trattini di quattro punti, spazi di due",
        "Trattini e spazi degli stessi tre punti",
        "Punti, che sono trattini di lunghezza nulla",
    ),
    ends="Tre estremità",
    end_names=("Squadrate", "Arrotondate", "Squadrate oltre la fine"),
    corners="Tre angoli",
    corner_names=("A punta", "Arrotondati", "Smussati"),
    ruled="Un estratto rigato a puntini",
    columns=("Descrizione", "Importo"),
    rows=(
        "Ufficio tecnico, febbraio",
        "Lastre e prove",
        "Consegna, due casse",
        "Deposito, un mese",
    ),
    total="Totale",
    caveat=(
        "Un punto è un trattino di lunghezza nulla, così mette inchiostro solo sotto "
        "un’estremità arrotondata: con estremità squadrate, lo stesso motivo non "
        "disegna nulla. Per questo le linee a puntini qui chiedono entrambe le cose."
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Líneas que no son continuas",
    lead=(
        "Un trazo dice su grosor y el color con que se dibuja, y también puede decir "
        "cómo se pone la tinta: los guiones y huecos que sigue, la forma de sus dos "
        "extremos y la forma donde se unen dos de sus segmentos. Nada de abajo se "
        "dibuja dos veces: cada línea es un trazo al que se le dice qué aspecto tener."
    ),
    patterns="Cuatro patrones",
    pattern_names=(
        "Continuo, lo que hace un trazo cuando no se le dice nada",
        "Guiones de cuatro puntos, huecos de dos",
        "Guiones y huecos de los mismos tres puntos",
        "Puntos, que son guiones de longitud nula",
    ),
    ends="Tres extremos",
    end_names=("Rectos", "Redondeados", "Rectos, más allá del final"),
    corners="Tres esquinas",
    corner_names=("En punta", "Redondeadas", "Recortadas"),
    ruled="Un extracto rayado con puntos",
    columns=("Descripción", "Importe"),
    rows=(
        "Oficina técnica, febrero",
        "Planchas y pruebas",
        "Entrega, dos cajas",
        "Almacenaje, un mes",
    ),
    total="Total",
    caveat=(
        "Un punto es un guion de longitud nula, así que solo pone tinta bajo un "
        "extremo redondeado: con extremos rectos, el mismo patrón no dibuja nada. Por "
        "eso las líneas punteadas de aquí piden las dos cosas."
    ),
)

# The page in German.
GERMAN = Words(
    title="Linien, die nicht durchgezogen sind",
    lead=(
        "Ein Strich sagt, wie dick er ist und in welcher Farbe er gezeichnet wird, "
        "und er kann auch sagen, wie die Farbe aufgetragen wird: welchen Strichen und "
        "Lücken er folgt, welche Form seine beiden Enden haben und welche Form dort "
        "entsteht, wo zwei seiner Abschnitte zusammentreffen. Nichts unten wird "
        "zweimal gezeichnet — jede Linie ist ein einziger Strich, dem gesagt wird, "
        "wie er aussehen soll."
    ),
    patterns="Vier Muster",
    pattern_names=(
        "Durchgezogen: ein Strich ohne Vorgaben",
        "Striche von vier Punkt, Lücken von zwei",
        "Striche und Lücken von jeweils drei Punkt",
        "Punkte, also Striche ganz ohne Länge",
    ),
    ends="Drei Enden",
    end_names=("Gerade abgeschnitten", "Abgerundet", "Gerade, übers Ende hinaus"),
    corners="Drei Ecken",
    corner_names=("Spitz", "Abgerundet", "Abgeschrägt"),
    ruled="Ein mit Punkten linierter Kontoauszug",
    columns=("Beschreibung", "Betrag"),
    rows=(
        "Zeichenbüro, Februar",
        "Platten und Andrucke",
        "Lieferung, zwei Kisten",
        "Lagerung, ein Monat",
    ),
    total="Summe",
    caveat=(
        "Ein Punkt ist ein Strich ohne Länge, er trägt also nur unter einem "
        "abgerundeten Ende Farbe auf: Mit gerade abgeschnittenen Enden zeichnet "
        "dasselbe Muster gar nichts. Darum verlangen die gepunkteten Linien hier "
        "beides."
    ),
)


# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH, _language.GERMAN: GERMAN, _language.SPANISH: SPANISH, _language.ITALIAN: ITALIAN, _language.PORTUGUESE: PORTUGUESE, _language.DUTCH: DUTCH}

# The left edge of everything on the page.
LEFT = 72.0

# How wide a block of text, and the table, are.
WIDTH = 451.0

# How far the sample lines run.
SAMPLE = 150.0

# The space that never opens a line, which parts an amount from its currency.
NO_BREAK = "\u00a0"

# The four amounts the statement carries, in cents.
AMOUNTS = (125_000, 48_050, 9_600, 21_025)


def block(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    size: float,
    top: float,
    text: str,
) -> float:
    """Sets a block of words at `top`, and hands back the ordinate it ends at."""
    flow = hqf_pdf.TextFlow(handle, size)
    lines = flow.break_lines(text, WIDTH)
    # The binding opens the text object itself, so opening another here would write a
    # pair of operators its twin in Rust does not.
    flow.draw(content, lines, LEFT, top, WIDTH)
    return top - flow.height(lines)


def patterns() -> list[hqf_pdf.LineStyle]:
    """The four patterns the page draws, in the order it draws them."""
    return [
        hqf_pdf.LineStyle(solid=True),
        hqf_pdf.LineStyle(dash=hqf_pdf.Dash.on_off(4.0, 2.0)),
        hqf_pdf.LineStyle(dash=hqf_pdf.Dash.even(3.0)),
        hqf_pdf.LineStyle(dash=hqf_pdf.Dash.dotted(4.0), cap=hqf_pdf.LineCap.Round),
    ]


def sample(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    y: float,
    style: hqf_pdf.LineStyle,
    name: str,
) -> None:
    """Draws one sample line at `y`, under `style`, and its name beside it."""
    content.save_state()
    content.set_line_width(1.5)
    content.set_line_style(style)
    content.move_to(LEFT, y)
    content.line_to(LEFT + SAMPLE, y)
    content.stroke()
    content.restore_state()

    room = WIDTH - SAMPLE - 16.0
    flow = hqf_pdf.TextFlow(handle, 9.5)
    flow.draw(content, flow.break_lines(name, room), LEFT + SAMPLE + 16.0, y + 3.0, room)


def corner(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    x: float,
    y: float,
    join: hqf_pdf.LineJoin,
    name: str,
) -> None:
    """Draws one corner at `x`, under `join`, and its name under it."""
    content.save_state()
    content.set_line_width(9.0)
    content.set_line_join(join)
    content.move_to(x, y)
    content.line_to(x + 24.0, y + 34.0)
    content.line_to(x + 48.0, y)
    content.stroke()
    content.restore_state()

    flow = hqf_pdf.TextFlow(handle, 8.5)
    flow.draw(content, flow.break_lines(name, 96.0), x, y - 8.0, 96.0)


def end(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    y: float,
    cap: hqf_pdf.LineCap,
    name: str,
) -> None:
    """Draws one line end at `y`, under `cap`, and its name beside it."""
    content.save_state()
    content.set_line_width(9.0)
    content.set_line_cap(cap)
    content.set_stroke(hqf_pdf.Rgb.gray(0.45))
    content.move_to(LEFT + 12.0, y)
    content.line_to(LEFT + 90.0, y)
    content.stroke()
    content.restore_state()

    # The thin line the ends are measured against: the ink of a squared-off end stops on
    # it, and the ink of the other two runs past it.
    content.save_state()
    content.set_line_width(0.4)
    content.set_stroke(hqf_pdf.Rgb(0.75, 0.1, 0.1))
    content.move_to(LEFT + 90.0, y - 10.0)
    content.line_to(LEFT + 90.0, y + 10.0)
    content.stroke()
    content.restore_state()

    room = WIDTH - 130.0
    flow = hqf_pdf.TextFlow(handle, 9.5)
    flow.draw(content, flow.break_lines(name, room), LEFT + 118.0, y + 3.0, room)


def money(cents: int) -> str:
    """An amount of cents, its thousands parted by a no-break space and its decimals
    by a point, which is how every language this example is written in writes one."""
    whole, fraction = divmod(cents, 100)
    digits = str(whole)
    out = []
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            out.append(NO_BREAK)
        out.append(digit)
    return f"{''.join(out)}.{fraction:02d}{NO_BREAK}EUR"


def statement(words: Words, text: hqf_pdf.FontHandle) -> hqf_pdf.Table:
    """The statement, ruled with dotted hairlines and a solid frame."""
    dotted_style = hqf_pdf.LineStyle(
        dash=hqf_pdf.Dash.dotted(2.5), cap=hqf_pdf.LineCap.Round
    )
    dotted = hqf_pdf.Stroke(0.6, color=hqf_pdf.Rgb.gray(0.45), style=dotted_style)
    columns = hqf_pdf.Columns(
        [hqf_pdf.ColumnWidth.fraction(1.0), hqf_pdf.ColumnWidth.points(110.0)],
        WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.75))
    table.rule(hqf_pdf.Rule.horizontal_other(), dotted)
    table.rule(hqf_pdf.Rule.vertical(1), dotted)

    pad = hqf_pdf.Padding.symmetric(5.0, 4.0)
    shade = hqf_pdf.Rgb(0.93, 0.94, 0.97)
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(text, 9.5, words.columns[0], padding=pad, fill=shade),
                hqf_pdf.Cell(
                    text,
                    9.5,
                    words.columns[1],
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    fill=shade,
                ),
            ],
            min_height=19.0,
        )
    )

    for label, amount in zip(words.rows, AMOUNTS):
        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell(text, 9.0, label, padding=pad),
                    hqf_pdf.Cell(
                        text,
                        9.0,
                        money(amount),
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                    ),
                ],
                min_height=16.0,
            )
        )

    # The total is held off the rows above it by a dashed border of its own, which is a
    # cell's line style rather than the table's.
    dashed = hqf_pdf.Stroke(
        0.8, color=None, style=hqf_pdf.LineStyle(dash=hqf_pdf.Dash.on_off(3.0, 2.0))
    )
    border = hqf_pdf.Border(top=dashed)
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(text, 9.5, words.total, padding=pad, border=border),
                hqf_pdf.Cell(
                    text,
                    9.5,
                    money(sum(AMOUNTS)),
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    border=border,
                ),
            ],
            min_height=18.0,
        )
    )
    return table


def build(words: Words, font: Path) -> bytes:
    """Draws the whole page."""
    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    text = doc.add_font(hqf_pdf.Font.from_path(font))

    content = hqf_pdf.Content()
    top = 782.0
    top = block(content, text, 17.0, top, words.title) - 12.0
    top = block(content, text, 9.5, top, words.lead) - 22.0

    top = block(content, text, 11.0, top, words.patterns) - 16.0
    for style, name in zip(patterns(), words.pattern_names):
        sample(content, text, top, style, name)
        top -= 20.0

    top -= 10.0
    top = block(content, text, 11.0, top, words.ends) - 18.0
    caps = (hqf_pdf.LineCap.Butt, hqf_pdf.LineCap.Round, hqf_pdf.LineCap.Projecting)
    for cap, name in zip(caps, words.end_names):
        end(content, text, top, cap, name)
        top -= 26.0

    top -= 6.0
    top = block(content, text, 11.0, top, words.corners) - 46.0
    joins = (hqf_pdf.LineJoin.Miter, hqf_pdf.LineJoin.Round, hqf_pdf.LineJoin.Bevel)
    for index, (join, name) in enumerate(zip(joins, words.corner_names)):
        corner(content, text, LEFT + index * 150.0, top, join, name)
    # The names sit under the corners, so the next heading starts below them.
    top -= 34.0

    top = block(content, text, 11.0, top, words.ruled) - 12.0
    placed = statement(words, text).fit(LEFT, top, top - 96.0)
    placed.draw(content)
    top = placed.bottom - 24.0

    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    block(content, text, 8.5, top, words.caveat)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    doc.add_page(page)
    return doc.to_bytes()


def main() -> None:
    """Writes the page."""
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(Path(_language.file_name("dotted_rules.pdf", language)).stem)

    data = build(words, _out.font_path())

    Path(out).parent.mkdir(parents=True, exist_ok=True)
    Path(out).write_bytes(data)
    print(f"wrote {out}: {len(data)} bytes")


if __name__ == "__main__":
    main()
