"""Sets paragraphs whose style changes inside them: sizes that shift mid-line, a
total that is underlined, and a word that turns underlined halfway through. Under them,
a heading set hollow and thickened, rules set where they are told rather than where the
font puts them, a long reference broken after its slashes and cut where nothing else
will do, and a paragraph centred in a box, with what its lines measure said under it.

The Python twin of the `write_rich_text` example in Rust. Each block is laid out in
the same box, so a line is as tall as the tallest style standing on it, and an
underline is drawn where each font says one goes.

The paragraphs are held in `Words`, once per language, and `HQF_PDF_LANG` picks which
set is set. Each is cut around the run whose style changes, so that a language says
what it has to say around the same three pieces.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The left edge of every box, the width they are broken to, the top of the first one,
# and the gap between one block and the next.
LEFT = 56.0
WIDTH = 420.0
TOP = 760.0
GAP = 26.0

# The sum the first paragraph is about. A total is not language.
AMOUNT = "1 240.00 EUR"

# The reference broken in a narrow box: an address that breaks after its slashes, and a
# code with nowhere to break but where the box cuts it.
REFERENCE = "hqf-pdf.com/examples/rich-text/overlong/ABCDEFGHJKLMNPQRSTUVWXYZ0123456789"

# How wide the box the reference is broken in is, in points.
NARROW = 150.0

# How tall the box the centred paragraph sits in is, in points.
BOX_HEIGHT = 60.0


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

    Every paragraph is cut around the run that carries the style being shown, so the
    piece that is underlined, enlarged or coloured is a piece of the sentence rather
    than a sentence of its own.
    """

    # The line at the head of the page.
    title: str
    # The first paragraph, cut around the amount it names.
    due: tuple[str, str]
    # The second, cut around the run set in the largest type.
    tallest: tuple[str, str, str]
    # The third, cut around the run that carries its own colour.
    coloured: tuple[str, str, str]
    # The fourth, cut in the middle of a word: the second piece turns underlined without
    # the word being broken at the join.
    joined: tuple[str, str, str]
    # The fifth, cut around the run named by the alignment it is set to.
    small: tuple[str, str, str]
    # A heading cut around its hollow run and its thickened one.
    hollow: tuple[str, str, str, str, str]
    # A sentence cut around its heavy underline and its thin strikeout.
    rules: tuple[str, str, str, str, str]
    # What stands over the reference broken in a narrow box.
    wrapped: str
    # The paragraph centred in a box.
    centred: str
    # What the centred paragraph's lines measure; `{count}`, `{tall}` and `{wide}` stand
    # for how many hold words, how tall they are together and how wide the widest runs.
    measured: str


# The page in English.
ENGLISH = Words(
    title="Rich text: styles, sizes, underlining, colour",
    due=(
        "The amount due is ",
        (
            ", payable within thirty days. The balance carries interest at the "
            "statutory rate from the day it falls due, and no reminder has to be sent "
            "for it to do so."
        ),
    ),
    tallest=(
        "A line is as tall as ",
        "the largest",
        " of the styles standing on it, and no taller.",
    ),
    coloured=(
        "A run can carry its own ",
        "colour",
        ", set apart from the black around it.",
    ),
    joined=(
        "A word may change style in the middle: under",
        "lined",
        " is still one word, and is never broken at the join.",
    ),
    small=(
        "The small print sits in small type, ",
        "flush right",
        ", below the body of the text.",
    ),
    hollow=(
        "A heading set ",
        "hollow",
        ", or ",
        "thickened",
        " without a bolder font",
    ),
    rules=(
        "A rule can sit where it is told: ",
        "a heavy underline",
        " clear of the descenders, or ",
        "a hairline",
        " through the letters.",
    ),
    wrapped=(
        "A reference broken after its slashes, and cut where nothing else will do:"
    ),
    centred="This paragraph is centred, across and down, in the box drawn around it.",
    measured="{count} lines, {tall} pt tall together, the widest {wide} pt wide.",
)

# The page in French.
FRENCH = Words(
    title="Texte enrichi : styles, tailles, soulignement, couleur",
    due=(
        "Le montant dû est de ",
        (
            ", payable sous trente jours. Le solde produit des intérêts au taux légal "
            "à compter du jour de son échéance, sans qu’aucun rappel n’ait à être "
            "envoyé."
        ),
    ),
    tallest=(
        "Une ligne est aussi haute que ",
        "le plus grand",
        " des styles qu’elle contient, et pas davantage.",
    ),
    coloured=(
        "Un passage peut avoir sa propre ",
        "couleur",
        ", distincte du noir qui l’entoure.",
    ),
    joined=(
        "Un mot peut changer de style en son milieu : souli",
        "gné",
        " reste un seul mot, et n’est jamais coupé à la jointure.",
    ),
    small=(
        "Les mentions légales sont en petits caractères, ",
        "alignées à droite",
        ", sous le corps du texte.",
    ),
    hollow=(
        "Un titre ",
        "évidé",
        ", ou ",
        "épaissi",
        " sans police plus grasse",
    ),
    rules=(
        "Un filet peut se placer où on le demande : ",
        "un soulignement épais",
        " sous les jambages, ou ",
        "un trait fin",
        " à travers les lettres.",
    ),
    wrapped=(
        "Une référence coupée après ses barres obliques, et tranchée là où il n’y a pas "
        "d’autre choix :"
    ),
    centred=(
        "Ce paragraphe est centré, en largeur et en hauteur, dans le cadre tracé "
        "autour de lui."
    ),
    measured="{count} lignes, {tall} pt de haut ensemble, la plus large de {wide} pt.",
)

# The page in Dutch.
DUTCH = Words(
    title="Opgemaakte tekst: stijlen, groottes, onderstreping, kleur",
    due=(
        "Het verschuldigde bedrag is",
        (
            ", te betalen binnen dertig dagen. Over het saldo is vanaf de vervaldag "
            "wettelijke rente verschuldigd, zonder dat daarvoor een herinnering hoeft "
            "te worden gestuurd."
        ),
    ),
    tallest=(
        "Een regel is zo hoog als",
        "de grootste",
        " van de stijlen die erop staan, en niet hoger.",
    ),
    coloured=(
        "Een stuk kan een eigen",
        "kleur",
        " hebben, los van het zwart eromheen.",
    ),
    joined=(
        "Een woord kan halverwege van stijl veranderen: onder",
        "streept",
        " is nog steeds één woord, en wordt nooit bij de naad gebroken.",
    ),
    small=(
        "De kleine lettertjes staan in kleine letter,",
        "rechts uitgelijnd",
        ", onder de hoofdtekst.",
    ),
    hollow=(
        "Een kop gezet",
        "hol",
        ", of",
        "verdikt",
        " zonder een vettere letter",
    ),
    rules=(
        "Een lijn kan staan waar ze moet:",
        "een zware onderstreping",
        " vrij van de onderstokken, of",
        "een haarlijn",
        " door de letters.",
    ),
    wrapped=(
        "Een kenmerk afgebroken na zijn schuine strepen, en gesneden waar niets anders kan:"
    ),
    centred="Deze alinea is gecentreerd, in de breedte en de hoogte, in het kader eromheen.",
    measured="{count} regels, samen {tall} pt hoog, de breedste {wide} pt breed.",
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Texto rico: estilos, tamanhos, sublinhado, cor",
    due=(
        "O montante em dívida é",
        (
            ", pagável no prazo de trinta dias. O saldo vence juros à taxa legal "
            "desde o vencimento, sem necessidade de enviar qualquer aviso."
        ),
    ),
    tallest=(
        "Uma linha é tão alta como",
        "o maior",
        " dos estilos que leva, e não mais.",
    ),
    coloured=(
        "Um troço pode levar a sua própria",
        "cor",
        ", separada do preto à volta.",
    ),
    joined=(
        "Uma palavra pode mudar de estilo a meio: sub",
        "linhado",
        " continua a ser uma palavra, e nunca se parte na junção.",
    ),
    small=(
        "As letras miudinhas vão em corpo pequeno,",
        "alinhadas à direita",
        ", por baixo do corpo do texto.",
    ),
    hollow=(
        "Um título composto",
        "oco",
        ", ou",
        "engrossado",
        " sem um tipo de letra mais negro",
    ),
    rules=(
        "Um filete pode ficar onde se lhe diz:",
        "um sublinhado grosso",
        " livre das descendentes, ou",
        "um filete fino",
        " através das letras.",
    ),
    wrapped=(
        "Uma referência partida depois das barras, e cortada onde não há outra forma:"
    ),
    centred="Este parágrafo está centrado, na largura e na altura, na caixa desenhada à sua volta.",
    measured="{count} linhas, {tall} pt de altura no total, a mais larga com {wide} pt.",
)

# The page in Italian.
ITALIAN = Words(
    title="Testo ricco: stili, corpi, sottolineatura, colore",
    due=(
        "L’importo dovuto è",
        (
            ", pagabile entro trenta giorni. Il saldo produce interessi al tasso "
            "legale dalla scadenza, senza bisogno di alcun sollecito."
        ),
    ),
    tallest=(
        "Una riga è alta quanto",
        "il più grande",
        " degli stili che porta, e non di più.",
    ),
    coloured=(
        "Un tratto può portare il proprio",
        "colore",
        ", separato dal nero che lo circonda.",
    ),
    joined=(
        "Una parola può cambiare stile a metà: sotto",
        "lineato",
        " resta una parola, e non si spezza mai alla giunzione.",
    ),
    small=(
        "Le clausole minori stanno in corpo piccolo,",
        "allineate a destra",
        ", sotto il corpo del testo.",
    ),
    hollow=(
        "Un titolo composto",
        "vuoto",
        ", o",
        "ispessito",
        " senza un font più nero",
    ),
    rules=(
        "Un filetto può stare dove gli si dice:",
        "una sottolineatura spessa",
        " libera dai discendenti, o",
        "un filetto sottile",
        " attraverso le lettere.",
    ),
    wrapped=(
        "Un riferimento spezzato dopo le barre, e tagliato dove non c’è altro modo:"
    ),
    centred="Questo paragrafo è centrato, in larghezza e in altezza, nel riquadro disegnato intorno.",
    measured="{count} righe, alte {tall} pt in tutto, la più larga di {wide} pt.",
)

# The page in Spanish.
SPANISH = Words(
    title="Texto enriquecido: estilos, tamaños, subrayado, color",
    due=(
        "El importe a pagar es ",
        (
            ", pagadero en treinta días. El saldo devenga intereses al tipo legal "
            "desde su vencimiento, sin necesidad de enviar ningún recordatorio."
        ),
    ),
    tallest=(
        "Una línea es tan alta como ",
        "el mayor",
        " de los estilos que lleva, y no más.",
    ),
    coloured=(
        "Un tramo puede llevar su propio ",
        "color",
        ", separado del negro que lo rodea.",
    ),
    joined=(
        "Una palabra puede cambiar de estilo a mitad: sub",
        "rayado",
        " sigue siendo una palabra, y nunca se corta en la unión.",
    ),
    small=(
        "La letra pequeña va en cuerpo pequeño, ",
        "alineada a la derecha",
        ", bajo el cuerpo del texto.",
    ),
    hollow=(
        "Un título compuesto ",
        "hueco",
        ", o ",
        "engrosado",
        " sin una fuente más negra",
    ),
    rules=(
        "Una raya puede ir donde se le diga: ",
        "un subrayado grueso",
        " libre de los descendentes, o ",
        "un filete",
        " a través de las letras.",
    ),
    wrapped=(
        "Una referencia cortada tras sus barras, y partida donde no queda otra:"
    ),
    centred="Este párrafo está centrado, a lo ancho y a lo alto, en la caja dibujada a su alrededor.",
    measured="{count} líneas, {tall} pt de alto en total, la más ancha de {wide} pt.",
)

# The page in German.
GERMAN = Words(
    title="Formatierter Text: Stile, Größen, Unterstreichung, Farbe",
    due=(
        "Der fällige Betrag ist ",
        (
            ", zahlbar binnen dreißig Tagen. Der Restbetrag wird ab Fälligkeit zum "
            "gesetzlichen Zinssatz verzinst, ohne dass dafür eine Mahnung nötig ist."
        ),
    ),
    tallest=(
        "Eine Zeile ist so hoch wie ",
        "der größte",
        " der Stile, die auf ihr stehen, und nicht höher.",
    ),
    coloured=(
        "Ein Abschnitt kann seine eigene ",
        "Farbe",
        " tragen, abgesetzt vom Schwarz ringsum.",
    ),
    joined=(
        "Ein Wort darf mitten im Wort den Stil wechseln: unter",
        "strichen",
        " bleibt ein Wort und wird an der Naht nie getrennt.",
    ),
    small=(
        "Das Kleingedruckte steht in kleiner Schrift, ",
        "rechtsbündig",
        ", unter dem Haupttext.",
    ),
    hollow=(
        "Eine Überschrift, ",
        "hohl",
        " gesetzt oder ",
        "verstärkt",
        " ohne fettere Schrift",
    ),
    rules=(
        "Eine Linie kann stehen, wo man sie hinstellt: ",
        "eine kräftige Unterstreichung",
        " frei von den Unterlängen, oder ",
        "eine Haarlinie",
        " durch die Buchstaben.",
    ),
    wrapped=(
        "Eine Referenz, nach ihren Schrägstrichen umbrochen und dort getrennt, wo nichts anderes geht:"
    ),
    centred="Dieser Absatz ist in dem um ihn gezeichneten Rahmen waagrecht und senkrecht zentriert.",
    measured="{count} Zeilen, zusammen {tall} pt hoch, die breiteste {wide} pt breit.",
)

# 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 blocks(font: hqf_pdf.FontHandle, words: Words) -> list[hqf_pdf.RichText]:
    """The paragraphs, in the order they are shown."""
    regular = hqf_pdf.Style(font, 11.0)
    small = hqf_pdf.Style(font, 8.0)
    large = hqf_pdf.Style(font, 17.0)
    marked = hqf_pdf.Style(font, 11.0, underline=True)
    accent = hqf_pdf.Style(font, 11.0, color=hqf_pdf.Rgb(0.0, 0.35, 0.7))

    return [
        hqf_pdf.RichText(align=hqf_pdf.Align.Justify)
        .span(words.due[0], regular)
        .span(AMOUNT, marked)
        .span(words.due[1], regular),
        hqf_pdf.RichText()
        .span(words.tallest[0], regular)
        .span(words.tallest[1], large)
        .span(words.tallest[2], regular),
        hqf_pdf.RichText()
        .span(words.coloured[0], regular)
        .span(words.coloured[1], accent)
        .span(words.coloured[2], regular),
        hqf_pdf.RichText()
        .span(words.joined[0], regular)
        .span(words.joined[1], marked)
        .span(words.joined[2], regular),
        hqf_pdf.RichText(align=hqf_pdf.Align.Right)
        .span(words.small[0], small)
        .span(words.small[1], small)
        .span(words.small[2], small),
    ]



def more(content, font, words, top) -> float:
    """Set the blocks under the first five from `top` down: the hollow and thickened
    heading, the rules set where they are told, the reference broken in a narrow box,
    and the paragraph centred in a box with what its lines measure; hand back where the
    last of them ends."""
    regular = hqf_pdf.Style(font, 11.0)
    small = hqf_pdf.Style(font, 8.0)
    ink = hqf_pdf.Rgb(0.0, 0.0, 0.0)
    hollow = hqf_pdf.Style(font, 17.0, outline=0.6, outline_color=ink)
    thickened = hqf_pdf.Style(
        font,
        17.0,
        color=hqf_pdf.Rgb(0.0, 0.35, 0.7),
        outline=0.8,
        outline_color=hqf_pdf.Rgb(0.0, 0.2, 0.45),
        outline_filled=True,
    )
    heading = hqf_pdf.Style(font, 17.0)
    # A heavy underline four points under the baseline, and a hairline three points over
    # it.
    heavy = hqf_pdf.Style(font, 11.0, underline_at=(-4.0, 1.5))
    hairline = hqf_pdf.Style(font, 11.0, strikethrough_at=(3.0, 0.4))
    blocks_under = [
        hqf_pdf.RichText()
        .span(words.hollow[0], heading)
        .span(words.hollow[1], hollow)
        .span(words.hollow[2], heading)
        .span(words.hollow[3], thickened)
        .span(words.hollow[4], heading),
        hqf_pdf.RichText()
        .span(words.rules[0], regular)
        .span(words.rules[1], heavy)
        .span(words.rules[2], regular)
        .span(words.rules[3], hairline)
        .span(words.rules[4], regular),
        hqf_pdf.RichText().span(words.wrapped, regular),
    ]
    for block in blocks_under:
        lines = block.break_lines(WIDTH)
        block.draw(content, lines, LEFT, top, WIDTH)
        top -= hqf_pdf.RichText.height(lines) + GAP / 2.0

    reference = hqf_pdf.RichText(
        overlong=hqf_pdf.Overlong.Break, cut_mark="-", break_after="/"
    ).span(REFERENCE, regular)
    lines = reference.break_lines(NARROW)
    reference.draw(content, lines, LEFT, top, NARROW)
    top -= hqf_pdf.RichText.height(lines) + GAP

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb(0.7, 0.7, 0.7))
    content.set_line_width(0.5)
    content.rect(LEFT, top - BOX_HEIGHT, WIDTH, BOX_HEIGHT)
    content.stroke()
    content.restore_state()
    centred = hqf_pdf.RichText(align=hqf_pdf.Align.Center).span(words.centred, regular)
    inside = WIDTH - 40.0
    lines = centred.break_lines(inside)
    start = hqf_pdf.RichText.top_for(lines, top, BOX_HEIGHT, hqf_pdf.VAlign.Middle)
    centred.draw(content, lines, LEFT + 20.0, start, inside)
    top -= BOX_HEIGHT + 14.0

    count = sum(1 for index in range(len(lines)) if not lines.is_empty(index))
    tall = sum(lines.height(index) for index in range(len(lines)))
    wide = max((lines.natural_width(index) for index in range(len(lines))), default=0.0)
    said = (
        words.measured.replace("{count}", str(count))
        .replace("{tall}", f"{tall:.0f}")
        .replace("{wide}", f"{wide:.0f}")
    )
    caption = hqf_pdf.RichText().span(said, small)
    lines = caption.break_lines(WIDTH)
    caption.draw(content, lines, LEFT, top, WIDTH)
    return top - hqf_pdf.RichText.height(lines)


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

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

    content = hqf_pdf.Content()
    content.draw_text(font, 14.0, LEFT, TOP + 24.0, words.title)

    paragraphs = blocks(font, words)
    top = TOP
    for block in paragraphs:
        lines = block.break_lines(WIDTH)
        block.draw(content, lines, LEFT, top, WIDTH)
        top -= hqf_pdf.RichText.height(lines) + GAP

    top = more(content, font, words, top)

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

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


if __name__ == "__main__":
    main()
