"""Lays an invoice table out across as many pages as its lines need.

The Python twin of the `write_table` example in Rust, and the one worth reading
first: the table is longer than a page, so it is fitted, drawn, and continued.
The row it stopped at is where the next page picks up, and the headings are drawn
again at the top of each one.

Every word the table draws is held in `Words`, once per language, and `HQF_PDF_LANG`
picks which one is drawn. The quantities and the prices are the same in both.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The margins, and the box the table is fitted into on every page.
MARGIN = 56.0
TOP = 780.0
BOTTOM = 64.0
PAGE_WIDTH = 595.276
TABLE_WIDTH = PAGE_WIDTH - 2 * MARGIN


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

    What is not language stays out of it: the quantities and the unit prices are drawn
    from ``ITEMS`` and read the same in every language.
    """

    # What each billed line is called, in the order ``ITEMS`` bills them.
    items: tuple[str, ...]
    # The four column headings.
    description: str
    quantity: str
    unit_price: str
    amount: str
    # The three totals under the billed lines.
    subtotal: str
    tax: str
    total: str


# The table in English.
ENGLISH = Words(
    items=(
        "Rendering engine development",
        "Font engine integration, including cutting each face down to the glyphs "
        "actually drawn",
        "Invoice template rework",
        "Historical data migration",
        "Acceptance testing and fixes",
        "Team training",
        "Standby cover for the release night",
        "Performance audit",
        "Technical documentation",
        "First year of support",
    ),
    description="Description",
    quantity="Qty",
    unit_price="Unit price",
    amount="Amount",
    subtotal="Subtotal",
    tax="VAT at 20 %",
    total="Total due",
)

# The table in French.
FRENCH = Words(
    items=(
        "Développement du moteur de rendu",
        ("Intégration du moteur de polices, avec réduction de chaque police aux seuls "
         "glyphes utilisés"),
        "Refonte du modèle de facture",
        "Migration des données historiques",
        "Recette et corrections",
        "Formation de l’équipe",
        "Astreinte la nuit de la mise en production",
        "Audit de performance",
        "Documentation technique",
        "Première année d’assistance",
    ),
    description="Désignation",
    quantity="Qté",
    unit_price="Prix unitaire",
    amount="Montant",
    subtotal="Total HT",
    tax="TVA 20 %",
    total="Total TTC",
)

# The table in Dutch.
DUTCH = Words(
    items=(
        "Ontwikkeling van de opmaakmotor",
        "Integratie van de lettertypemotor, inclusief het inkorten van elke letter "
        "tot de werkelijk getekende glyphs",
        "Herziening van het factuursjabloon",
        "Migratie van historische gegevens",
        "Acceptatietests en correcties",
        "Teamtraining",
        "Stand-by voor de lanceringsnacht",
        "Prestatieaudit",
        "Technische documentatie",
        "Eerste jaar ondersteuning",
    ),
    description="Omschrijving",
    quantity="Aantal",
    unit_price="Stukprijs",
    amount="Bedrag",
    subtotal="Subtotaal",
    tax="Btw 20 %",
    total="Te betalen",
)

# The table in Portuguese.
PORTUGUESE = Words(
    items=(
        "Desenvolvimento do motor de paginação",
        "Integração do motor de tipos de letra, incluindo reduzir cada tipo aos "
        "glifos de facto desenhados",
        "Remodelação do modelo de fatura",
        "Migração de dados históricos",
        "Testes de aceitação e correções",
        "Formação da equipa",
        "Prevenção para a noite do lançamento",
        "Auditoria de desempenho",
        "Documentação técnica",
        "Primeiro ano de suporte",
    ),
    description="Descrição",
    quantity="Qtd.",
    unit_price="Preço unitário",
    amount="Montante",
    subtotal="Subtotal",
    tax="IVA a 20 %",
    total="Total a pagar",
)

# The table in Italian.
ITALIAN = Words(
    items=(
        "Sviluppo del motore di impaginazione",
        "Integrazione del motore dei font, inclusa la riduzione di ogni font ai glifi "
        "effettivamente disegnati",
        "Revisione del modello di fattura",
        "Migrazione dei dati storici",
        "Collaudo e correzioni",
        "Formazione del team",
        "Reperibilità per la notte del rilascio",
        "Verifica delle prestazioni",
        "Documentazione tecnica",
        "Primo anno di assistenza",
    ),
    description="Descrizione",
    quantity="Qtà",
    unit_price="Prezzo unitario",
    amount="Importo",
    subtotal="Imponibile",
    tax="IVA al 20 %",
    total="Totale dovuto",
)

# The table in Spanish.
SPANISH = Words(
    items=(
        "Desarrollo del motor de maquetación",
        "Integración del motor de fuentes, incluido el recorte de cada fuente a los "
        "glifos realmente dibujados",
        "Rediseño de la plantilla de factura",
        "Migración de datos históricos",
        "Pruebas de aceptación y correcciones",
        "Formación del equipo",
        "Guardia para la noche del lanzamiento",
        "Auditoría de rendimiento",
        "Documentación técnica",
        "Primer año de soporte",
    ),
    description="Descripción",
    quantity="Cant.",
    unit_price="Precio unitario",
    amount="Importe",
    subtotal="Subtotal",
    tax="IVA al 20 %",
    total="Total a pagar",
)

# The table in German.
GERMAN = Words(
    items=(
        "Entwicklung der Rendering-Engine",
        "Integration der Font-Engine, einschließlich der Beschränkung jedes Schnitts "
        "auf die tatsächlich gezeichneten Glyphen",
        "Überarbeitung der Rechnungsvorlage",
        "Migration der Altdaten",
        "Abnahmetests und Korrekturen",
        "Schulung des Teams",
        "Bereitschaft in der Nacht der Auslieferung",
        "Leistungsprüfung",
        "Technische Dokumentation",
        "Erstes Jahr Support",
    ),
    description="Beschreibung",
    quantity="Menge",
    unit_price="Einzelpreis",
    amount="Betrag",
    subtotal="Zwischensumme",
    tax="MwSt. 20 %",
    total="Zu zahlen",
)


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


@dataclass(frozen=True)
class Item:
    """One line of the invoice."""

    quantity: int
    unit_price: float


# The lines the invoice bills, in the order ``Words.items`` names them.
ITEMS = [
    Item(12, 620.0),
    Item(8, 620.0),
    Item(3, 480.0),
    Item(5, 540.0),
    Item(6, 480.0),
    Item(2, 750.0),
    Item(1, 1200.0),
    Item(4, 690.0),
    Item(3, 420.0),
    Item(12, 350.0),
]


def amount(value: float) -> str:
    """An amount, as an invoice writes it: "4 250.00 EUR"."""
    units, hundredths = f"{value:.2f}".split(".")
    grouped = ""
    for index, digit in enumerate(units):
        if index > 0 and (len(units) - index) % 3 == 0:
            grouped += " "
        grouped += digit
    return f"{grouped}.{hundredths} EUR"


# The colour the grand total's figure is drawn in.
TOTAL_INK = hqf_pdf.Rgb(0.0, 0.3, 0.6)


def invoice_table(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Table:
    """The invoice's table: a heading row, the billed lines, and the totals."""
    # The designation takes whatever the three figure columns leave it.
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(46.0),
            hqf_pdf.ColumnWidth.points(94.0),
            hqf_pdf.ColumnWidth.points(94.0),
        ],
        TABLE_WIDTH,
    )

    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, color=hqf_pdf.Rgb.gray(0.75))
    table.rule(hqf_pdf.Rule.horizontal_other(), hairline)
    table.rule(hqf_pdf.Rule.vertical_other(), hairline)
    # Under the headings, and above the totals.
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.8))
    table.rule(hqf_pdf.Rule.horizontal_from_end(1), hqf_pdf.Stroke(0.8))

    pad = hqf_pdf.Padding.symmetric(5.0, 4.0)
    shade = hqf_pdf.Rgb.gray(0.88)

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

    table.push(
        hqf_pdf.Row(
            cells=[
                heading(words.description),
                heading(words.quantity, hqf_pdf.Align.Right),
                heading(words.unit_price, hqf_pdf.Align.Right),
                heading(words.amount, hqf_pdf.Align.Right),
            ],
            min_height=20.0,
        )
    )

    # The lines are billed five times over, so that the table runs past a page and its
    # continuation can be seen.
    total = 0.0
    for index in range(len(ITEMS) * 5):
        item = ITEMS[index % len(ITEMS)]
        label = words.items[index % len(ITEMS)]
        line_total = item.quantity * item.unit_price
        total += line_total

        def figure(value: str) -> hqf_pdf.Cell:
            return hqf_pdf.Cell(
                font,
                9.0,
                value,
                padding=pad,
                align=hqf_pdf.Align.Right,
                valign=hqf_pdf.VAlign.Middle,
            )

        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell(font, 9.0, label, padding=pad),
                    figure(str(item.quantity)),
                    figure(amount(item.unit_price)),
                    figure(amount(line_total)),
                ],
                min_height=18.0,
                # Every other line is shaded, which is what a row fill is for.
                fill=hqf_pdf.Rgb.gray(0.97) if index % 2 else None,
            )
        )

    def value_cell(
        figure: str, inked: bool, size: float, **placed: object
    ) -> hqf_pdf.Cell:
        # The grand total's figure is drawn in a colour of its own, and its currency in
        # the ink of the rest of the table: one cell, two styles.
        if not inked:
            return hqf_pdf.Cell(font, size, figure, **placed)
        number, __, currency = figure.rpartition(" ")
        plain = hqf_pdf.Style(font, size)
        ink = hqf_pdf.Style(font, size, color=TOTAL_INK)
        text = hqf_pdf.RichText().span(number, ink).span(f" {currency}", plain)
        return hqf_pdf.Cell.rich(text, **placed)

    tax = total * 0.2
    for label, value, size, is_grand_total in (
        (words.subtotal, total, 9.0, False),
        (words.tax, tax, 9.0, False),
        (words.total, total + tax, 10.0, True),
    ):
        # The grand total is boxed in a border of its own, held off the grid by a margin
        # so that it reads as a total rather than as one more line of the table. The box
        # is drawn side by side: the label carries its left edge and the figure its
        # right, so the two cells trace one box between them rather than a box each.
        if is_grand_total:
            rule = hqf_pdf.Stroke(0.8)
            label_border = hqf_pdf.Border(top=rule, bottom=rule, left=rule)
            value_border = hqf_pdf.Border(top=rule, bottom=rule, right=rule)
            box_margin = hqf_pdf.Margin.symmetric(0.0, 2.0)
        else:
            label_border = value_border = hqf_pdf.Border.none()
            box_margin = hqf_pdf.Margin()

        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell(
                        font,
                        size,
                        label,
                        span=3,
                        align=hqf_pdf.Align.Right,
                        padding=pad,
                        margin=box_margin,
                        border=label_border,
                    ),
                    value_cell(
                        amount(value),
                        is_grand_total,
                        size,
                        align=hqf_pdf.Align.Right,
                        padding=pad,
                        margin=box_margin,
                        border=value_border,
                    ),
                ],
                min_height=18.0,
            )
        )

    return table


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

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

    table = invoice_table(font, words)

    # Fit, draw, and continue on a new page for as long as rows remain.
    start = 0
    pages = 0
    while True:
        placed = table.fit(MARGIN, TOP, TOP - BOTTOM, start)

        content = hqf_pdf.Content()
        placed.draw(content)

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

        if placed.done:
            break
        start = placed.next_row

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


if __name__ == "__main__":
    main()
