"""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 dit son épaisseur et sa couleur, et il peut aussi dire comment "
        "l'encre est posée : les tirets et les blancs qu'il suit, la forme de ses deux "
        "bouts, et la forme de l'angle où deux de ses segments se rejoignent. Rien "
        "ci-dessous n'est dessiné deux fois : chaque ligne est un seul trait, à qui "
        "l'on a dit de quoi avoir l'air."
    ),
    patterns="Quatre motifs",
    pattern_names=(
        "Plein, ce que fait un trait à qui l'on ne dit rien",
        "Tirets de quatre points, blancs de deux",
        "Tirets et blancs des mêmes trois points",
        "Pointillé, c'est-à-dire des tirets sans aucune longueur",
    ),
    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 pose d'encre que sous un bout "
        "arrondi. À qui lui demande des bouts coupés net, le même motif ne dessine "
        "rien du tout. C'est pourquoi les traits en pointillé de cette page demandent "
        "les deux."
    ),
)


# 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}

# 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, hqf_pdf.Rgb.gray(0.45), 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(
            [
                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(
                [
                    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, None, hqf_pdf.LineStyle(dash=hqf_pdf.Dash.on_off(3.0, 2.0))
    )
    border = hqf_pdf.Border(top=dashed)
    table.push(
        hqf_pdf.Row(
            [
                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()
