"""Sets the same two paragraphs six ways, one shape to a block: indents, the room
around a paragraph, the alignment of its last line, and where its first baseline
sits. Under them, one sentence is placed three times in a box taller than it: against
the box's top, centred in it, and against its bottom, where `TextFlow.top_for` says
the block starts.

A second page sets the same paragraphs four more ways: the first baseline an ascender
down and the block ending on its last baseline, both baselines at distances of their
own, the letters outlined and left hollow, and the letters filled and outlined over to
thicken them.

The Python twin of the `write_paragraphs` example in Rust.

The paragraphs and the heading over each block are written in the language
`HQF_PDF_LANG` names: what a shape does to a paragraph is only visible on a paragraph
somebody can read.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The width of a block, and the gap between the two columns of them.
COLUMN = 225.0
# The left edge of the two columns.
LEFT = (60.0, 310.0)
# The top of the first block of each column.
TOP = 780.0
# How far apart the blocks of a column are stacked.
STEP = 190.0

# The body size every block is set at, and the leading it is set on.
SIZE = 10.0
LEADING = 13.0

# The size a block's heading is set at, and the leading it is set on.
HEADING = 7.5
HEADING_LEADING = 9.5

# How far under its heading the text of a block starts.
HEADING_GAP = 8.0

# The top of the three boxes a sentence is placed in, their width, the gap between two
# of them, and their height.
PLACED_TOP = 200.0
PLACED_WIDTH = 145.0
PLACED_GAP = 20.0
PLACED_HEIGHT = 90.0

# Where the sentence sits in each of the three boxes, from the left.
PLACES = (hqf_pdf.VAlign.Top, hqf_pdf.VAlign.Middle, hqf_pdf.VAlign.Bottom)


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

    # Two paragraphs, so that every block shows both what happens inside one and what
    # happens between two.
    text: str
    # What each block is headed by, in the order they are set.
    headings: tuple[str, str, str, str, str, str]
    # What each block of the second page is headed by, in the order they are set.
    more_headings: tuple[str, str, str, str]
    # The sentence placed in the three boxes.
    placed: str
    # What each of the three boxes is headed by, from the left.
    places: tuple[str, str, str]


# The page in English.
ENGLISH = Words(
    text=(
        "The deposit is held on the account named overleaf and is returned within "
        "thirty days of the keys being handed back.\nDeductions are itemised in "
        "writing, and anything not itemised is not deducted."
    ),
    headings=(
        "Nothing set: the shape a flow has by default.",
        "First line indented; the paragraphs are told apart by that alone.",
        "First line hung out to the left of the block.",
        "Room left above and below each paragraph.",
        "Justified, with the last line of each paragraph centred.",
        (
            "First baseline on the top of the capitals, last line clear of its "
            "descenders."
        ),
    ),
    more_headings=(
        "First baseline one ascender down; the block ends on its last baseline.",
        "First baseline 18 points down, and 9 points kept under the last.",
        "Letters outlined in a hairline and left hollow.",
        "Letters filled, and outlined over to thicken them.",
    ),
    placed="Keys are handed back at the office, against a signed receipt.",
    places=(
        "Against the top of its box.",
        "Centred in its box.",
        "Against the bottom of its box.",
    ),
)

# The page in French.
FRENCH = Words(
    text=(
        "Le dépôt de garantie est conservé sur le compte indiqué au verso et restitué "
        "dans les trente jours qui suivent la remise des clés.\nToute retenue est "
        "détaillée par écrit, et ce qui n’est pas détaillé n’est pas retenu."
    ),
    headings=(
        "Rien de réglé : la forme qu’un bloc prend par défaut.",
        "Première ligne en retrait ; c’est le seul signe qui sépare les paragraphes.",
        "Première ligne débordant à gauche du bloc.",
        "De l’air laissé au-dessus et au-dessous de chaque paragraphe.",
        "Justifié, la dernière ligne de chaque paragraphe centrée.",
        (
            "Première ligne de base sur le haut des capitales, dernière ligne dégagée "
            "de ses jambages."
        ),
    ),
    more_headings=(
        (
            "Première ligne de base à une hauteur d’ascendante du haut ; le bloc finit "
            "sur sa dernière ligne de base."
        ),
        (
            "Première ligne de base à 18 points du haut, et 9 points gardés sous la "
            "dernière."
        ),
        "Lettres tracées d’un filet fin et laissées creuses.",
        "Lettres pleines, cernées d’un trait qui les épaissit.",
    ),
    placed="Les clés sont rendues à l’agence, contre un reçu signé.",
    places=(
        "Contre le haut de sa boîte.",
        "Centré dans sa boîte.",
        "Contre le bas de sa boîte.",
    ),
)

# The page in Dutch.
DUTCH = Words(
    text=(
        "De borg staat op de rekening op de achterzijde en wordt binnen dertig dagen "
        "na teruggave van de sleutels terugbetaald.\nInhoudingen worden schriftelijk "
        "gespecificeerd, en wat niet gespecificeerd is, wordt niet ingehouden."
    ),
    headings=(
        "Niets ingesteld: de vorm die een tekst standaard heeft.",
        "Eerste regel ingesprongen; de alinea’s zijn alleen daaraan te onderscheiden.",
        "Eerste regel links buiten het blok hangend.",
        "Ruimte boven en onder elke alinea.",
        "Uitgevuld, met de laatste regel van elke alinea gecentreerd.",
        (
            "Eerste basislijn tegen de bovenkant van de hoofdletters, laatste regel "
            "vrij van zijn onderstokken."
        ),
    ),
    more_headings=(
        "Eerste basislijn één stok omlaag; het blok eindigt op zijn laatste basislijn.",
        "Eerste basislijn 18 punten omlaag, en 9 punten vrijgehouden onder de laatste.",
        "Letters omlijnd met een haarlijn en hol gelaten.",
        "Letters gevuld, en erover omlijnd om ze dikker te maken.",
    ),
    placed="Sleutels worden op kantoor teruggegeven, tegen een getekend ontvangstbewijs.",
    places=(
        "Tegen de bovenkant van zijn kader.",
        "Gecentreerd in zijn kader.",
        "Tegen de onderkant van zijn kader.",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    text=(
        "A caução fica na conta indicada no verso e é devolvida nos trinta dias "
        "seguintes à entrega das chaves.\nAs deduções são discriminadas por escrito, "
        "e o que não for discriminado não é deduzido."
    ),
    headings=(
        "Nada definido: a forma que um texto tem por omissão.",
        "Primeira linha avançada; os parágrafos distinguem-se só por isso.",
        "Primeira linha pendurada à esquerda do bloco.",
        "Espaço acima e abaixo de cada parágrafo.",
        "Justificado, com a última linha de cada parágrafo centrada.",
        (
            "Primeira linha de base no topo das maiúsculas, última linha livre das "
            "descendentes."
        ),
    ),
    more_headings=(
        "Primeira linha de base um ascendente abaixo; o bloco acaba na sua última linha de base.",
        "Primeira linha de base 18 pontos abaixo, e 9 pontos guardados sob a última.",
        "Letras contornadas por um filete e deixadas ocas.",
        "Letras preenchidas, e contornadas por cima para as engrossar.",
    ),
    placed="As chaves entregam-se no escritório, contra recibo assinado.",
    places=(
        "Encostado ao topo da sua caixa.",
        "Centrado na sua caixa.",
        "Encostado ao fundo da sua caixa.",
    ),
)

# The page in Italian.
ITALIAN = Words(
    text=(
        "Il deposito cauzionale è tenuto sul conto indicato sul retro ed è restituito "
        "entro trenta giorni dalla riconsegna delle chiavi.\nLe detrazioni sono "
        "elencate per iscritto, e ciò che non è elencato non è detratto."
    ),
    headings=(
        "Nessuna impostazione: la forma predefinita di un testo.",
        "Prima riga rientrata; i paragrafi si distinguono solo per questo.",
        "Prima riga sporgente a sinistra del blocco.",
        "Spazio sopra e sotto ogni paragrafo.",
        "Giustificato, con l’ultima riga di ogni paragrafo centrata.",
        (
            "Prima linea di base in cima alle maiuscole, ultima riga libera dai "
            "discendenti."
        ),
    ),
    more_headings=(
        "Prima linea di base un ascendente più in basso; il blocco finisce sulla sua ultima linea di base.",
        "Prima linea di base 18 punti più in basso, e 9 punti tenuti sotto l’ultima.",
        "Lettere contornate da un filetto e lasciate vuote.",
        "Lettere piene, e contornate sopra per ispessirle.",
    ),
    placed="Le chiavi si riconsegnano in ufficio, contro ricevuta firmata.",
    places=(
        "Contro il bordo superiore del suo riquadro.",
        "Centrato nel suo riquadro.",
        "Contro il bordo inferiore del suo riquadro.",
    ),
)

# The page in Spanish.
SPANISH = Words(
    text=(
        "La fianza se guarda en la cuenta indicada al dorso y se devuelve en los "
        "treinta días siguientes a la entrega de las llaves.\nLas deducciones se "
        "detallan por escrito, y lo que no se detalla no se deduce."
    ),
    headings=(
        "Nada ajustado: la forma que tiene un texto por defecto.",
        "Primera línea sangrada; los párrafos se distinguen solo por eso.",
        "Primera línea colgada a la izquierda del bloque.",
        "Espacio encima y debajo de cada párrafo.",
        "Justificado, con la última línea de cada párrafo centrada.",
        (
            "Primera línea base en lo alto de las mayúsculas, última línea libre de "
            "sus descendentes."
        ),
    ),
    more_headings=(
        "Primera línea base un ascendente más abajo; el bloque acaba en su última línea base.",
        "Primera línea base 18 puntos más abajo, y 9 puntos guardados bajo la última.",
        "Letras contorneadas con un filete y dejadas huecas.",
        "Letras rellenas, y contorneadas encima para engrosarlas.",
    ),
    placed="Las llaves se devuelven en la oficina, contra un recibo firmado.",
    places=(
        "Contra el borde superior de su caja.",
        "Centrado en su caja.",
        "Contra el borde inferior de su caja.",
    ),
)

# The page in German.
GERMAN = Words(
    text=(
        "Die Kaution liegt auf dem umseitig genannten Konto und wird binnen dreißig "
        "Tagen nach Rückgabe der Schlüssel erstattet.\nAbzüge werden schriftlich "
        "einzeln aufgeführt, und was nicht aufgeführt ist, wird nicht abgezogen."
    ),
    headings=(
        "Nichts eingestellt: die Form, die ein Textfluss standardmäßig hat.",
        "Erste Zeile eingerückt; allein daran unterscheiden sich die Absätze.",
        "Erste Zeile links aus dem Block herausgehängt.",
        "Raum über und unter jedem Absatz.",
        "Blocksatz, die letzte Zeile jedes Absatzes zentriert.",
        (
            "Erste Grundlinie auf Versalhöhe, letzte Zeile frei von ihren Unterlängen."
        ),
    ),
    more_headings=(
        "Erste Grundlinie eine Oberlänge tiefer; der Block endet auf seiner letzten Grundlinie.",
        "Erste Grundlinie 18 Punkt tiefer, und 9 Punkt unter der letzten freigehalten.",
        "Buchstaben mit Haarlinie umrandet und hohl gelassen.",
        "Buchstaben gefüllt und darüber umrandet, um sie zu verstärken.",
    ),
    placed="Schlüssel werden im Büro gegen Quittung zurückgegeben.",
    places=(
        "An der Oberkante seines Rahmens.",
        "In seinem Rahmen zentriert.",
        "An der Unterkante seines Rahmens.",
    ),
)

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


def block(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    flow: hqf_pdf.TextFlow,
    x: float,
    top: float,
    label: str,
    text: str,
) -> None:
    """Sets one block: its heading, the text under it, and the box the flow fills."""
    heading = hqf_pdf.TextFlow(
        handle, HEADING, leading=HEADING_LEADING, color=hqf_pdf.Rgb.gray(0.35)
    )
    heading_lines = heading.break_lines(label, COLUMN)
    heading.draw(content, heading_lines, x, top, COLUMN)

    text_top = top - heading.height(heading_lines) - HEADING_GAP
    lines = flow.break_lines(text, COLUMN)
    flow.draw(content, lines, x, text_top, COLUMN)

    # The box the flow reports filling, so that the room it keeps around a paragraph is
    # visible and not merely stated.
    height = flow.height(lines)
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.8))
    content.set_line_width(0.5)
    content.rect(x, text_top - height, COLUMN, height)
    content.stroke()
    content.restore_state()


def placed(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    x: float,
    label: str,
    align: hqf_pdf.VAlign,
    text: str,
) -> None:
    """Sets one of the three boxes: its heading, its outline, and the sentence placed
    in it as `align` says."""
    heading = hqf_pdf.TextFlow(
        handle, HEADING, leading=HEADING_LEADING, color=hqf_pdf.Rgb.gray(0.35)
    )
    heading_lines = heading.break_lines(label, PLACED_WIDTH)
    heading.draw(content, heading_lines, x, PLACED_TOP, PLACED_WIDTH)

    box_top = PLACED_TOP - heading.height(heading_lines) - HEADING_GAP
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.8))
    content.set_line_width(0.5)
    content.rect(x, box_top - PLACED_HEIGHT, PLACED_WIDTH, PLACED_HEIGHT)
    content.stroke()
    content.restore_state()

    flow = hqf_pdf.TextFlow(handle, SIZE, leading=LEADING)
    lines = flow.break_lines(text, PLACED_WIDTH)
    top = flow.top_for(lines, box_top, PLACED_HEIGHT, align)
    flow.draw(content, lines, x, top, PLACED_WIDTH)



def more_blocks(handle, words) -> tuple:
    """The four blocks of the second page: what each is headed by, and the shape it
    sets the two paragraphs in."""
    return (
        (
            words.more_headings[0],
            hqf_pdf.TextFlow(
                handle,
                SIZE,
                leading=LEADING,
                first_baseline=hqf_pdf.FirstBaseline.ascender(),
                last_baseline=hqf_pdf.LastBaseline.none(),
            ),
        ),
        (
            words.more_headings[1],
            hqf_pdf.TextFlow(
                handle,
                SIZE,
                leading=LEADING,
                first_baseline=hqf_pdf.FirstBaseline.points(18.0),
                last_baseline=hqf_pdf.LastBaseline.points(9.0),
            ),
        ),
        (
            words.more_headings[2],
            hqf_pdf.TextFlow(
                handle,
                SIZE,
                leading=LEADING,
                outline=0.4,
                outline_color=hqf_pdf.Rgb(0.0, 0.25, 0.55),
            ),
        ),
        (
            words.more_headings[3],
            hqf_pdf.TextFlow(
                handle,
                SIZE,
                leading=LEADING,
                outline=0.5,
                outline_color=hqf_pdf.Rgb.gray(0.0),
                outline_filled=True,
            ),
        ),
    )


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

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

    blocks = (
        (
            words.headings[0],
            hqf_pdf.TextFlow(handle, SIZE, leading=LEADING),
        ),
        (
            words.headings[1],
            hqf_pdf.TextFlow(handle, SIZE, leading=LEADING, first_line_indent=18.0),
        ),
        (
            words.headings[2],
            hqf_pdf.TextFlow(
                handle,
                SIZE,
                leading=LEADING,
                left_indent=24.0,
                first_line_indent=-24.0,
            ),
        ),
        (
            words.headings[3],
            hqf_pdf.TextFlow(
                handle, SIZE, leading=LEADING, space_before=4.0, space_after=8.0
            ),
        ),
        (
            words.headings[4],
            hqf_pdf.TextFlow(
                handle,
                SIZE,
                leading=LEADING,
                align=hqf_pdf.Align.Justify,
                last_align=hqf_pdf.Align.Center,
                right_indent=12.0,
            ),
        ),
        (
            words.headings[5],
            hqf_pdf.TextFlow(
                handle,
                SIZE,
                leading=LEADING,
                first_baseline=hqf_pdf.FirstBaseline.cap_height(),
                last_baseline=hqf_pdf.LastBaseline.descender(),
            ),
        ),
    )

    content = hqf_pdf.Content()
    for index, (label, flow) in enumerate(blocks):
        block(
            content,
            handle,
            flow,
            LEFT[index // 3],
            TOP - STEP * (index % 3),
            label,
            words.text,
        )
    for index, (label, align) in enumerate(zip(words.places, PLACES)):
        x = LEFT[0] + (PLACED_WIDTH + PLACED_GAP) * index
        placed(content, handle, x, label, align, words.placed)

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

    content = hqf_pdf.Content()
    for index, (label, flow) in enumerate(more_blocks(handle, words)):
        block(
            content,
            handle,
            flow,
            LEFT[index // 2],
            TOP - STEP * (index % 2),
            label,
            words.text,
        )
    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()
