"""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.

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"


@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]


# 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.",
    ),
)

# 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 porte intérêt 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 qui s'y tiennent, et pas davantage.",
    ),
    coloured=(
        "Un passage peut porter 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.",
    ),
)


# 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 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)
        .push(words.due[0], regular)
        .push(AMOUNT, marked)
        .push(words.due[1], regular),
        hqf_pdf.RichText()
        .push(words.tallest[0], regular)
        .push(words.tallest[1], large)
        .push(words.tallest[2], regular),
        hqf_pdf.RichText()
        .push(words.coloured[0], regular)
        .push(words.coloured[1], accent)
        .push(words.coloured[2], regular),
        hqf_pdf.RichText()
        .push(words.joined[0], regular)
        .push(words.joined[1], marked)
        .push(words.joined[2], regular),
        hqf_pdf.RichText(align=hqf_pdf.Align.Right)
        .push(words.small[0], small)
        .push(words.small[1], small)
        .push(words.small[2], small),
    ]


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

    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()
