"""Lays a whole report out by stacking blocks, without writing a single ordinate
by hand.

The Python twin of the `write_stack` example in Rust. The page holds a title, a
rule, two paragraphs, a heading, a table of twenty-six rows and a footnote, and
they are pushed onto a stack in the order they are read. The stack breaks them
across as many pages as they need: the table is cut row by row, its heading row
repeated, and the closing paragraph is kept together so that it is never left
with one line on a page of its own.

The only ordinate the example writes is the one the page number sits on, which
belongs to the sheet rather than to what is said on it.

Every word is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. The hours and the amounts are figures, and stand the same in every language.

Usage: python examples/write_stack.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_stack.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 report draws, in one language.

    What is not language stays out of it: every hour and every amount is a figure, and
    the row numbers run from one whatever the words say.
    """

    # The report's title.
    title: str
    # The paragraph under the title.
    intro: str
    # The heading over the table.
    section: str
    # The three column headings of the table.
    headings: tuple[str, str, str]
    # What each row of the table is called, before its number.
    task: str
    # The paragraph under the table, kept together.
    closing: str
    # The line at the foot of the report.
    footnote: str
    # The word the page number opens with.
    page: str
    # The word between a page's number and how many pages there are.
    of: str

    def page_label(self, index: int, total: int) -> str:
        """Return what the foot of page `index` of `total` reads."""
        return f"{self.page} {index + 1} {self.of} {total}"

    def row_label(self, index: int) -> str:
        """Return what row `index` of the table is called."""
        return f"{self.task} {index + 1:02d}"


# The report in English.
ENGLISH = Words(
    title="Work carried out this quarter",
    intro=(
        "Every block on this page was pushed onto a stack in the order it is read, "
        "and the stack decided where each of them goes. Nothing here was placed "
        "against a measured height: a paragraph that grows pushes what follows it "
        "down the page, and onto the next one when the room runs out."
    ),
    section="What was done, task by task",
    headings=("Task", "Hours", "Amount"),
    task="Task",
    closing=(
        "The table above was cut wherever the room ran out, and its heading row was "
        "drawn again at the top of every page it was carried onto. This paragraph "
        "was kept together, so it is never left with a single line at the foot of a "
        "page while the rest of it starts the next one."
    ),
    footnote="Hours are billed at 85.00 € each, and the amounts are exclusive of tax.",
    page="Page",
    of="of",
)

# The report in French.
FRENCH = Words(
    title="Les travaux du trimestre",
    intro=(
        "Chaque bloc de cette page a été empilé dans l'ordre où on le lit, et c'est "
        "la pile qui a décidé où chacun se pose. Rien n'a été placé contre une "
        "hauteur mesurée à la main : un paragraphe qui s'allonge pousse la suite "
        "vers le bas, et sur la page suivante quand la place vient à manquer."
    ),
    section="Le détail, tâche par tâche",
    headings=("Tâche", "Heures", "Montant"),
    task="Tâche",
    closing=(
        "Le tableau ci-dessus a été coupé là où la place manquait, et sa rangée de "
        "titres redessinée en haut de chaque page où il se poursuit. Ce paragraphe, "
        "lui, tient d'un seul tenant : il ne laisse jamais une ligne seule en bas "
        "d'une page pendant que le reste ouvre la suivante."
    ),
    footnote="L'heure est facturée 85.00 € et les montants s'entendent hors taxes.",
    page="Page",
    of="sur",
)


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

# How many rows of work the table carries.
ROWS = 26

# The colour of the rule under the title.
ACCENT = hqf_pdf.Rgb(0.12, 0.33, 0.55)

# The colour the footnote and the page number are set in.
MUTED = hqf_pdf.Rgb(0.45, 0.45, 0.45)

# How wide the report is, in points: the sheet less a margin either side.
WIDTH = 483.0

# The left edge of everything the report draws.
LEFT = 56.0

# The ordinate the page number sits on, which belongs to the sheet rather than to what
# is said on it.
FOOT = 40.0

# The box the first page gives the report, and the one every page after it gives.
FIRST_BOX = hqf_pdf.StackFrame(LEFT, 780.0, WIDTH, 700.0)
NEXT_BOX = hqf_pdf.StackFrame(LEFT, 780.0, WIDTH, 700.0)


def work(index: int) -> tuple[int, int]:
    """Return the hours row `index` took, and what they came to."""
    hours = 2 + index % 5
    return hours, hours * 85


def work_table(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Table:
    """Return the table of work, its heading row repeated on every page."""
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(70.0),
            hqf_pdf.ColumnWidth.points(90.0),
        ],
        WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8))
    table.rule(
        hqf_pdf.Rule.horizontal_other(), hqf_pdf.Stroke(0.25, hqf_pdf.Rgb.gray(0.75))
    )
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.8))

    pad = hqf_pdf.Padding.symmetric(6.0, 5.0)

    def heading(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            9.0,
            label,
            align=align,
            padding=pad,
            valign=hqf_pdf.VAlign.Middle,
            fill=hqf_pdf.Rgb.gray(0.88),
        )

    table.push(
        hqf_pdf.Row(
            [
                heading(words.headings[0], hqf_pdf.Align.Left),
                heading(words.headings[1], hqf_pdf.Align.Right),
                heading(words.headings[2], hqf_pdf.Align.Right),
            ],
            min_height=20.0,
        )
    )

    for index in range(ROWS):
        hours, amount = work(index)
        table.push(
            hqf_pdf.Row(
                [
                    hqf_pdf.Cell(font, 9.0, words.row_label(index), padding=pad),
                    hqf_pdf.Cell(
                        font, 9.0, f"{hours}", align=hqf_pdf.Align.Right, padding=pad
                    ),
                    hqf_pdf.Cell(
                        font,
                        9.0,
                        f"{amount}.00",
                        align=hqf_pdf.Align.Right,
                        padding=pad,
                    ),
                ]
            )
        )
    return table


def report(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Stack:
    """Return the whole report, block by block, in the order it is read."""
    body = hqf_pdf.TextFlow(font, 10.5, leading=15.0, align=hqf_pdf.Align.Justify)

    stack = hqf_pdf.Stack()
    stack.push(
        hqf_pdf.Block.text(
            hqf_pdf.TextFlow(font, 16.0), words.title, keep_together=True
        )
    )
    stack.push(hqf_pdf.Block.space(8.0))
    stack.push(hqf_pdf.Block.rule(hqf_pdf.Stroke(1.2, ACCENT)))
    stack.push(hqf_pdf.Block.space(14.0))
    stack.push(hqf_pdf.Block.text(body, words.intro))
    stack.push(hqf_pdf.Block.space(18.0))
    stack.push(
        hqf_pdf.Block.text(
            hqf_pdf.TextFlow(font, 12.0), words.section, keep_together=True
        )
    )
    stack.push(hqf_pdf.Block.space(8.0))
    stack.push(hqf_pdf.Block.table(work_table(font, words)))
    stack.push(hqf_pdf.Block.space(18.0))
    stack.push(hqf_pdf.Block.text(body, words.closing, keep_together=True))
    stack.push(hqf_pdf.Block.space(14.0))
    stack.push(hqf_pdf.Block.rule(hqf_pdf.Stroke(0.6, MUTED)))
    stack.push(hqf_pdf.Block.space(8.0))
    stack.push(
        hqf_pdf.Block.text(hqf_pdf.TextFlow(font, 8.0, color=MUTED), words.footnote)
    )
    return stack


def page_number(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    index: int,
    total: int,
) -> None:
    """Draw the page number at the foot of the sheet."""
    flow = hqf_pdf.TextFlow(font, 8.0, color=MUTED, align=hqf_pdf.Align.Center)
    label = words.page_label(index, total)
    flow.draw(content, flow.break_lines(label, WIDTH), LEFT, FOOT, WIDTH)


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("stack.pdf", language)).stem)

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

    pages = report(font, words).paginate(FIRST_BOX, NEXT_BOX)

    for index, placed in enumerate(pages):
        content = hqf_pdf.Content()
        placed.draw(content)
        page_number(content, font, words, index, len(pages))

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

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


if __name__ == "__main__":
    main()
