"""Prints two orders of unequal length side by side in frames of one height, and ends
both of them on the same bottom edge.

The Python twin of the `write_filled_frame` example in Rust. A pad of pre-printed
stationery has the frame already on the paper: a box for the lines, a rule under it,
and the total below that rule. What goes in the box is a different length every time.
Left alone, an order of four lines leaves a hand's breadth of white above the rule and
an order of seven fills it, and the pad looks like two different documents.

So the box is filled instead. The rows of the order share whatever room the frame has
left, in equal parts, once they have all been measured, and the last of them ends on
the bottom edge. The headings and the total are left exactly where the stationery puts
them.

The notes at the foot of the page do the same for words rather than rows: the lines of
each note are moved apart until they reach the bottom of their box, so two notes of
unequal length end on one line. A limit is given with the box, and a note far too short
for it keeps the spacing it came with rather than being stretched into a ladder.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. The amounts are the same in both.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# What the shorter order's lines cost, in euros.
SHORT_AMOUNTS = (420.0, 96.0, 158.0, 240.0)

# What the longer order's lines cost, in euros.
LONG_AMOUNTS = (180.0, 64.0, 112.0, 45.0, 320.0, 88.0, 150.0)


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

    title: str
    lead: str
    orders: str
    short_order: str
    long_order: str
    item: str
    amount: str
    short_items: tuple[str, ...]
    long_items: tuple[str, ...]
    total: str
    notes: str
    short_note: str
    long_note: str
    caveat: str


# The page in English.
ENGLISH = Words(
    title="Two orders, one frame, one bottom edge",
    lead=(
        "The two frames below are the same height, and the orders in them are not the "
        "same length. Each frame is filled: whatever room the lines leave is shared "
        "out among them in equal parts, once they have all been measured, so the last "
        "line of an order of four ends where the last line of an order of seven ends. "
        "The headings and the total stay where the stationery puts them, and only the "
        "billed lines grow."
    ),
    orders="Four lines and seven, ending together",
    short_order="Order 4412",
    long_order="Order 4413",
    item="Item",
    amount="Amount",
    short_items=("Site survey", "Cable, 40 m", "Wall boxes", "Fitting, one day"),
    long_items=(
        "Site survey",
        "Cable, 15 m",
        "Wall boxes",
        "Junction box",
        "Fitting, two days",
        "Cover plates",
        "Test and report",
    ),
    total="Total",
    notes="Two notes of unequal length, ending together",
    short_note=(
        "Goods stay ours until they are paid for in full. Anything found broken is to "
        "be written on the driver's sheet before it is signed, and told to us the same "
        "week. A pallet left with a neighbour is left at the buyer's own risk."
    ),
    long_note=(
        "Payment is due thirty days from the date of issue, by transfer to the account "
        "named at the foot of the invoice. A line queried in writing suspends nothing "
        "but the line itself, and the rest of the invoice falls due on the day it "
        "always did. Work already booked is held for a fortnight after that day and "
        "released afterwards."
    ),
    caveat=(
        "The lines of a note are moved apart, and nothing else: the room kept around a "
        "paragraph, the drop under the last line and the height of the words "
        "themselves stand where they are. A limit is given along with the box, so two "
        "lines in a tall box keep the spacing they came with rather than being "
        "stretched into a ladder."
    ),
)

# The page in French.
FRENCH = Words(
    title="Deux commandes, un seul cadre, un seul bas de page",
    lead=(
        "Les deux cadres ci-dessous ont la même hauteur, et les commandes qu'ils "
        "portent n'ont pas la même longueur. Chaque cadre est rempli : la place que "
        "les lignes laissent est partagée entre elles en parts égales, une fois "
        "qu'elles ont toutes été mesurées, si bien que la dernière ligne d'une "
        "commande de quatre finit là où finit la dernière ligne d'une commande de "
        "sept. Les en-têtes et le total restent où le papier les pose, et seules les "
        "lignes facturées grandissent."
    ),
    orders="Quatre lignes et sept, qui finissent ensemble",
    short_order="Commande 4412",
    long_order="Commande 4413",
    item="Poste",
    amount="Montant",
    short_items=(
        "Visite des lieux",
        "Câble, 40 m",
        "Boîtiers muraux",
        "Pose, une journée",
    ),
    long_items=(
        "Visite des lieux",
        "Câble, 15 m",
        "Boîtiers muraux",
        "Boîte de dérivation",
        "Pose, deux journées",
        "Plaques de finition",
        "Essais et rapport",
    ),
    total="Total",
    notes="Deux mentions de longueurs différentes, qui finissent ensemble",
    short_note=(
        "La marchandise nous appartient jusqu'au paiement intégral. Tout élément "
        "trouvé cassé se porte sur la feuille du chauffeur avant signature, et nous "
        "est signalé dans la semaine. Une palette laissée chez un voisin l'est aux "
        "risques de l'acheteur."
    ),
    long_note=(
        "Le paiement est dû trente jours après la date d'émission, par virement au "
        "compte indiqué au bas de la facture. Une ligne contestée par écrit ne suspend "
        "que cette ligne, et le reste de la facture reste dû au jour prévu. Les "
        "travaux déjà réservés sont tenus quinze jours après ce jour, puis rendus."
    ),
    caveat=(
        "Les lignes d'une mention sont écartées, et rien d'autre : la place gardée "
        "autour d'un paragraphe, la retombée sous la dernière ligne et la hauteur des "
        "mots eux-mêmes restent où elles sont. Une limite est donnée avec le cadre : "
        "deux lignes dans un grand cadre gardent donc l'espacement qu'elles avaient, "
        "au lieu d'être étirées en échelle."
    ),
)

# 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 is, and how wide the two frames are together.
WIDTH = 451.0

# How wide one frame is.
FRAME_WIDTH = 216.0

# How far apart the two frames stand.
FRAME_GAP = WIDTH - 2 * FRAME_WIDTH

# How tall each of the two order frames is.
FRAME_HEIGHT = 200.0

# How tall each of the two note boxes is.
NOTE_HEIGHT = 110.0

# The size a note is set at.
NOTE_SIZE = 8.5

# The furthest apart the lines of a note are ever moved.
NOTE_LIMIT = 26.0

# The size an order is set at.
ORDER_SIZE = 8.5

# The least tall a billed line is before the frame is shared out.
ROW_HEIGHT = 16.0

# The grey the page draws its second-rank words in.
GREY = hqf_pdf.Rgb.gray(0.42)

# The grey a note's box is outlined in.
OUTLINE = hqf_pdf.Rgb.gray(0.72)


def block(
    content: hqf_pdf.Content,
    flow: hqf_pdf.TextFlow,
    x: float,
    top: float,
    width: float,
    text: str,
) -> float:
    """Sets a block of words at `top`, and hands back the ordinate it ends at."""
    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, x, top, width)
    return top - flow.height(lines)


def amount(value: float) -> str:
    """An amount, as an order writes it: "1 158.00"."""
    units, hundredths = f"{value:.2f}".split(".")
    grouped = []
    for index, digit in enumerate(units):
        if index > 0 and (len(units) - index) % 3 == 0:
            grouped.append(" ")
        grouped.append(digit)
    return f"{''.join(grouped)}.{hundredths}"


def order(
    font: hqf_pdf.FontHandle,
    words: Words,
    items: tuple[str, ...],
    amounts: tuple[float, ...],
) -> hqf_pdf.Table:
    """One of the two orders: a heading row, the billed lines, and the total."""
    columns = hqf_pdf.Columns(
        [hqf_pdf.ColumnWidth.fraction(1.0), hqf_pdf.ColumnWidth.points(62.0)],
        FRAME_WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    table.footer(1)
    # Every box the table is fitted into is filled to its bottom edge.
    table.fill_frame(True)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.7))
    table.rule(
        hqf_pdf.Rule.horizontal_other(), hqf_pdf.Stroke(0.25, hqf_pdf.Rgb.gray(0.78))
    )
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.7))
    table.rule(hqf_pdf.Rule.horizontal_from_end(1), hqf_pdf.Stroke(0.7))

    pad = hqf_pdf.Padding.symmetric(5.0, 4.0)
    shade = hqf_pdf.Rgb.gray(0.9)
    table.push(
        hqf_pdf.Row(
            [
                hqf_pdf.Cell(
                    font,
                    ORDER_SIZE,
                    words.item,
                    padding=pad,
                    fill=shade,
                    valign=hqf_pdf.VAlign.Middle,
                ),
                hqf_pdf.Cell(
                    font,
                    ORDER_SIZE,
                    words.amount,
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    fill=shade,
                    valign=hqf_pdf.VAlign.Middle,
                ),
            ],
            min_height=18.0,
        )
    )

    total = 0.0
    for label, value in zip(items, amounts):
        total += value
        table.push(
            hqf_pdf.Row(
                [
                    hqf_pdf.Cell(
                        font,
                        ORDER_SIZE,
                        label,
                        padding=pad,
                        valign=hqf_pdf.VAlign.Middle,
                    ),
                    hqf_pdf.Cell(
                        font,
                        ORDER_SIZE,
                        amount(value),
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                        valign=hqf_pdf.VAlign.Middle,
                    ),
                ],
                min_height=ROW_HEIGHT,
            )
        )

    table.push(
        hqf_pdf.Row(
            [
                hqf_pdf.Cell(
                    font,
                    ORDER_SIZE,
                    words.total,
                    padding=pad,
                    valign=hqf_pdf.VAlign.Middle,
                ),
                hqf_pdf.Cell(
                    font,
                    ORDER_SIZE,
                    amount(total),
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    valign=hqf_pdf.VAlign.Middle,
                ),
            ],
            min_height=18.0,
        )
    )

    return table


def note(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    x: float,
    top: float,
    text: str,
) -> None:
    """Draws one note in a box `NOTE_HEIGHT` points tall, its lines moved apart until
    the last of them reaches the bottom."""
    content.set_stroke(OUTLINE)
    content.set_line_width(0.4)
    content.rect(x, top - NOTE_HEIGHT, FRAME_WIDTH, NOTE_HEIGHT)
    content.stroke()

    # The box is filled from the top of the letters to the foot of them, so the block
    # the spread is measured against is the block a reader sees.
    flow = hqf_pdf.TextFlow(
        font,
        NOTE_SIZE,
        first_baseline=hqf_pdf.FirstBaseline.ascender(),
        last_baseline=hqf_pdf.LastBaseline.descender(),
    )
    lines = flow.break_lines(text, FRAME_WIDTH - 12.0)
    spread = flow.leading(flow.fill_leading(lines, NOTE_HEIGHT, NOTE_LIMIT))
    spread.draw(content, lines, x + 6.0, top, FRAME_WIDTH - 12.0)


def build(document: hqf_pdf.Document, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws the whole page."""
    title = hqf_pdf.TextFlow(font, 18.0)
    lead = hqf_pdf.TextFlow(font, 10.0)
    label = hqf_pdf.TextFlow(font, 12.0)
    small = hqf_pdf.TextFlow(font, 8.5, color=GREY)

    content = hqf_pdf.Content()
    top = 790.0
    top = block(content, title, LEFT, top, WIDTH, words.title) - 12.0
    top = block(content, lead, LEFT, top, WIDTH, words.lead) - 22.0
    top = block(content, label, LEFT, top, WIDTH, words.orders) - 12.0

    right = LEFT + FRAME_WIDTH + FRAME_GAP
    block(content, small, LEFT, top, FRAME_WIDTH, words.short_order)
    top = block(content, small, right, top, FRAME_WIDTH, words.long_order) - 6.0

    for x, items, amounts in (
        (LEFT, words.short_items, SHORT_AMOUNTS),
        (right, words.long_items, LONG_AMOUNTS),
    ):
        placed = order(font, words, items, amounts).fit(x, top, FRAME_HEIGHT)
        placed.draw(content)
    top -= FRAME_HEIGHT + 26.0

    top = block(content, label, LEFT, top, WIDTH, words.notes) - 14.0
    note(content, font, LEFT, top, words.short_note)
    note(content, font, right, top, words.long_note)
    top -= NOTE_HEIGHT + 24.0

    closing = hqf_pdf.TextFlow(font, 9.0, color=GREY)
    block(content, closing, LEFT, top, WIDTH, words.caveat)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)


def main() -> None:
    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("filled_frame.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    build(document, font, words)

    written = document.write(out)
    print(f"wrote {out}: {written} bytes")


if __name__ == "__main__":
    main()
