"""Draws one parts list twice: columns of equal width, then columns measured
from what they hold.

The Python twin of the `write_measured_columns` example in Rust. The rows are
the same in both tables. In the first the four columns share the width equally,
so the references and the figures sit in far more room than they need and the
descriptions wrap for want of it. In the second the reference, the quantity and
the price are each as wide as their own widest cell, and the description is
given everything they leave.

What the page reads is held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn. The references, the quantities and the prices are not language:
they are the same figures whoever reads the list.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The margins, the top of the first table, and the room between the two.
MARGIN = 56.0
TOP = 740.0
GAP = 64.0
PAGE_WIDTH = 595.276
TABLE_WIDTH = PAGE_WIDTH - 2 * MARGIN


@dataclass(frozen=True)
class Part:
    """One line of the parts list, save what it is called."""

    reference: str
    quantity: str
    price: str


# The figures the list holds. They are short and all of a length, whatever language the
# list is read in; what each part is called is in `Words`.
PARTS = [
    Part("HQF-1042", "2", "48.00"),
    Part("HQF-1043", "2", "26.50"),
    Part("HQF-2210", "1", "9.20"),
    Part("HQF-3007", "1", "142.00"),
    Part("HQF-3011", "3", "11.75"),
]


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

    The references, the quantities and the prices are not here: they are the same
    figures in every language, and they are what the two narrow columns are measured
    from.
    """

    # The line over each of the two tables.
    captions: tuple[str, str]
    # The four column headings, in the order the columns are drawn.
    headings: tuple[str, str, str, str]
    # What each part is, in the order the rows are drawn.
    descriptions: tuple[str, str, str, str, str]


# The page in English.
ENGLISH = Words(
    captions=(
        "Columns of equal width",
        "Columns measured from their cells",
    ),
    headings=("Reference", "Description", "Qty", "Unit price"),
    descriptions=(
        "Aluminium mounting plate, drilled for the four-point thread",
        "Quick-release shoe",
        "Sealing ring, nitrile, sold in packs of ten",
        "Bench supply, twelve volts, regulated",
        "Adapter lead, two metres",
    ),
)

# The page in French.
FRENCH = Words(
    captions=(
        "Des colonnes de largeur égale",
        "Des colonnes mesurées sur leurs cellules",
    ),
    headings=("Référence", "Désignation", "Qté", "Prix unitaire"),
    descriptions=(
        "Plaque de montage en aluminium, percée pour la fixation quatre points",
        "Sabot à dégagement rapide",
        "Joint torique en nitrile, vendu par dix",
        "Alimentation d'établi, douze volts, régulée",
        "Cordon adaptateur, deux mètres",
    ),
)


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


def parts_list(
    font: hqf_pdf.FontHandle, words: Words, columns: hqf_pdf.Columns
) -> hqf_pdf.Table:
    """The parts list, laid out across `columns`."""
    table = hqf_pdf.Table(columns)
    table.header(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8))
    hairline = hqf_pdf.Stroke(0.25, hqf_pdf.Rgb.gray(0.75))
    table.rule(hqf_pdf.Rule.horizontal_other(), hairline)
    table.rule(hqf_pdf.Rule.vertical_other(), hairline)
    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.Align.Left) -> 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]),
                heading(words.headings[1]),
                heading(words.headings[2], hqf_pdf.Align.Right),
                heading(words.headings[3], hqf_pdf.Align.Right),
            ],
            min_height=20.0,
        )
    )

    for part, description in zip(PARTS, words.descriptions):
        table.push(
            hqf_pdf.Row(
                [
                    hqf_pdf.Cell(font, 9.0, part.reference, padding=pad),
                    hqf_pdf.Cell(font, 9.0, description, padding=pad),
                    hqf_pdf.Cell(
                        font,
                        9.0,
                        part.quantity,
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                    ),
                    hqf_pdf.Cell(
                        font,
                        9.0,
                        part.price,
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                        align_on=".",
                    ),
                ],
                min_height=18.0,
            )
        )

    return table


def caption(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, label: str, y: float
) -> None:
    """Draws `label` at (MARGIN, y) in 11pt."""
    content.draw_text(font, 11.0, MARGIN, y, label)


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

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

    # Four columns sharing the width equally, and the same four with three of them
    # measured from their own cells.
    equal = parts_list(font, words, hqf_pdf.Columns.equal(4, TABLE_WIDTH))
    measured = parts_list(
        font,
        words,
        hqf_pdf.Columns(
            [
                hqf_pdf.ColumnWidth.content(),
                hqf_pdf.ColumnWidth.fraction(1.0),
                hqf_pdf.ColumnWidth.content(),
                hqf_pdf.ColumnWidth.content(),
            ],
            TABLE_WIDTH,
        ),
    )

    content = hqf_pdf.Content()

    caption(content, font, words.captions[0], TOP + 18.0)
    first = equal.fit(MARGIN, TOP, TOP - MARGIN, 0)
    first.draw(content)

    second_top = first.bottom - GAP
    caption(content, font, words.captions[1], second_top + 18.0)
    second = measured.fit(MARGIN, second_top, second_top - MARGIN, 0)
    second.draw(content)

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

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {equal.row_count} rows twice")


if __name__ == "__main__":
    main()
