"""Writes a document whose pages link out of themselves and to each other.

The Python twin of the `write_links` example in Rust: the same document, through
the binding rather than through the library directly.

A link draws nothing, so nothing on the page proves it is there: only reading software
does, by following it. The first page carries a table of contents whose lines lead to
the pages after it, and an address that leaves the document; each of the pages after it
leads back. The navigation panel holds the same contents, and a last row that opens the
same address.

The chapter titles and the lines around them are held in `Words`, once per language,
and `HQF_PDF_LANG` picks which set is drawn. A chapter title is written once and read
twice: it is what the contents shows, and what the navigation panel shows.

Each chapter's page shows one side of a link. The first carries a link that covers two
lines and nothing between them, and one that goes to the contents by the name it is
filed under. The second carries five links, one per border a link can draw, each pressed
its own way, the border read back from the link, all on a layer of their own. The third
goes back to the contents eight times, each showing the page its own way, every link
carrying the same flags, read back beside them. The navigation panel sets the first
chapter before the others once they are listed, and ends on a separating line and a
bold blue italic row to the named contents.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The address the contents leaves the document by. It is not language.
ADDRESS = "https://example.org/hqf-pdf"


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

    A chapter title is written once and read twice: the contents draws it, and the
    navigation panel carries it. Both read the same field, so the two can never fall
    out of step.
    """

    # The line at the head of the contents, and the name its bookmark takes.
    contents: str
    # The line that says which text on the page can be clicked.
    what_is_clickable: str
    # The chapters the contents lists, in the order they are laid out.
    chapters: tuple[str, str, str]
    # The line each chapter page leads back by.
    back: str
    # The row of the navigation panel that opens the address.
    online: str
    # The title the document carries in its information dictionary.
    document_title: str
    # The two lines one link covers on the first chapter's page.
    over: tuple[str, str]
    # The line that reads back how many areas that link covers; `{n}` stands for the
    # count.
    covered: str
    # The line leading back to the contents by the name it is filed under.
    named: str
    # The heading over the links of the second chapter's page.
    borders: str
    # What each style of border is called: solid, dashed, bevelled, inset, underlined.
    styles: tuple[str, str, str, str, str]
    # The heading over the links of the third chapter's page.
    views: str
    # How each of those links shows the contents page.
    fits: tuple[str, ...]
    # The line that reads back the flags those links carry; `{bits}` stands for them.
    flags: str
    # The name of the layer the second chapter's links belong to.
    layer: str
    # The line of the navigation panel that separates the chapters from the rest.
    separator: str


# The document in English.
ENGLISH = Words(
    contents="Contents",
    what_is_clickable="Blue text is clickable; black text is not.",
    chapters=(
        "What a link is",
        "What a link draws",
        "Where a link goes",
    ),
    back="Back to the contents",
    online="The same, online",
    document_title="A document that links to itself",
    over=(
        "One link covers this line",
        "and this one, and nothing between them.",
    ),
    covered="The link above covers {n} areas.",
    named="Back to the contents, by the name it is filed under",
    borders="Five borders a link can draw, each read back from the link:",
    styles=(
        "solid",
        "dashed",
        "bevelled",
        "inset",
        "underlined",
    ),
    views="Back to the contents, the page shown eight ways:",
    fits=(
        "whole page",
        "full width",
        "full height",
        "a rectangle",
        "whole drawing",
        "drawing width",
        "drawing height",
        "fixed place",
    ),
    flags="Each of these links carries the flags {bits}.",
    layer="Links",
    separator="Elsewhere",
)

# The document in French.
FRENCH = Words(
    contents="Sommaire",
    what_is_clickable="Le texte bleu est cliquable, le noir ne l’est pas.",
    chapters=(
        "Ce qu’est un lien",
        "Ce qu’un lien affiche",
        "Où mène un lien",
    ),
    back="Retour au sommaire",
    online="La même chose, en ligne",
    document_title="Un document qui renvoie à lui-même",
    over=(
        "Un même lien couvre cette ligne",
        "et celle-ci, et rien entre elles.",
    ),
    covered="Le lien ci-dessus couvre {n} zones.",
    named="Retour au sommaire, par le nom sous lequel il est rangé",
    borders="Cinq bordures qu’un lien peut tracer, chacune relue sur le lien :",
    styles=(
        "plein",
        "tireté",
        "biseauté",
        "en creux",
        "souligné",
    ),
    views="Retour au sommaire, la page montrée de huit façons :",
    fits=(
        "page entière",
        "pleine largeur",
        "pleine hauteur",
        "un rectangle",
        "dessin entier",
        "largeur du dessin",
        "hauteur du dessin",
        "position fixe",
    ),
    flags="Chacun de ces liens porte les indicateurs {bits}.",
    layer="Liens",
    separator="Ailleurs",
)

# The document in Dutch.
DUTCH = Words(
    contents="Inhoud",
    what_is_clickable="Blauwe tekst is klikbaar; zwarte tekst niet.",
    chapters=(
        "Wat een link is",
        "Wat een link tekent",
        "Waar een link heen gaat",
    ),
    back="Terug naar de inhoud",
    online="Hetzelfde, online",
    document_title="Een document dat naar zichzelf linkt",
    over=(
        "Eén link dekt deze regel",
        "en deze, en niets ertussen.",
    ),
    covered="De link hierboven dekt {n} gebieden.",
    named="Terug naar de inhoud, via de naam waaronder die bewaard is",
    borders="Vijf randen van een link, elk teruggelezen uit de link:",
    styles=(
        "doorgetrokken",
        "gestreept",
        "afgeschuind",
        "verzonken",
        "onderstreept",
    ),
    views="Terug naar de inhoud, de pagina op acht manieren getoond:",
    fits=(
        "hele pagina",
        "volle breedte",
        "volle hoogte",
        "een rechthoek",
        "hele tekening",
        "breedte van de tekening",
        "hoogte van de tekening",
        "vaste plek",
    ),
    flags="Elk van deze links heeft de vlaggen {bits}.",
    layer="Links",
    separator="Elders",
)

# The document in Portuguese.
PORTUGUESE = Words(
    contents="Índice",
    what_is_clickable="O texto azul é clicável; o preto não.",
    chapters=(
        "O que é uma ligação",
        "O que uma ligação desenha",
        "Para onde vai uma ligação",
    ),
    back="Voltar ao índice",
    online="O mesmo, online",
    document_title="Um documento que se liga a si próprio",
    over=(
        "Uma ligação cobre esta linha",
        "e esta, e nada entre elas.",
    ),
    covered="A ligação acima cobre {n} zonas.",
    named="Voltar ao índice, pelo nome com que está arquivado",
    borders="Cinco contornos de ligação, cada um relido da ligação:",
    styles=(
        "contínuo",
        "tracejado",
        "biselado",
        "embutido",
        "sublinhado",
    ),
    views="Voltar ao índice, com a página mostrada de oito formas:",
    fits=(
        "página inteira",
        "toda a largura",
        "toda a altura",
        "um retângulo",
        "desenho inteiro",
        "largura do desenho",
        "altura do desenho",
        "posição fixa",
    ),
    flags="Cada uma destas ligações leva os indicadores {bits}.",
    layer="Ligações",
    separator="Noutro lado",
)

# The document in Italian.
ITALIAN = Words(
    contents="Indice",
    what_is_clickable="Il testo blu è cliccabile; quello nero no.",
    chapters=(
        "Che cos’è un collegamento",
        "Che cosa disegna un collegamento",
        "Dove porta un collegamento",
    ),
    back="Torna all’indice",
    online="Lo stesso, online",
    document_title="Un documento che rimanda a sé stesso",
    over=(
        "Un collegamento copre questa riga",
        "e questa, e niente in mezzo.",
    ),
    covered="Il collegamento qui sopra copre {n} zone.",
    named="Torna all’indice, col nome sotto cui è archiviato",
    borders="Cinque bordi di link, ciascuno riletto dal link:",
    styles=(
        "continuo",
        "tratteggiato",
        "smussato",
        "incassato",
        "sottolineato",
    ),
    views="Torna all’indice, con la pagina mostrata in otto modi:",
    fits=(
        "pagina intera",
        "tutta la larghezza",
        "tutta l’altezza",
        "un rettangolo",
        "disegno intero",
        "larghezza del disegno",
        "altezza del disegno",
        "posizione fissa",
    ),
    flags="Ognuno di questi collegamenti porta gli indicatori {bits}.",
    layer="Collegamenti",
    separator="Altrove",
)

# The document in Spanish.
SPANISH = Words(
    contents="Índice",
    what_is_clickable="El texto azul es clicable; el negro no.",
    chapters=(
        "Qué es un enlace",
        "Qué dibuja un enlace",
        "Adónde lleva un enlace",
    ),
    back="Volver al índice",
    online="Lo mismo, en línea",
    document_title="Un documento que se enlaza a sí mismo",
    over=(
        "Un enlace cubre esta línea",
        "y esta otra, y nada entre ellas.",
    ),
    covered="El enlace de arriba cubre {n} zonas.",
    named="Volver al índice, por el nombre con que está archivado",
    borders="Cinco bordes de enlace, cada uno leído del enlace:",
    styles=(
        "continuo",
        "discontinuo",
        "biselado",
        "hundido",
        "subrayado",
    ),
    views="Volver al índice, con la página mostrada de ocho formas:",
    fits=(
        "página entera",
        "todo el ancho",
        "toda la altura",
        "un rectángulo",
        "dibujo entero",
        "ancho del dibujo",
        "altura del dibujo",
        "lugar fijo",
    ),
    flags="Cada uno de estos enlaces lleva los indicadores {bits}.",
    layer="Enlaces",
    separator="En otro sitio",
)

# The document in German.
GERMAN = Words(
    contents="Inhalt",
    what_is_clickable="Blauer Text ist anklickbar; schwarzer Text nicht.",
    chapters=(
        "Was ein Link ist",
        "Was ein Link zeichnet",
        "Wohin ein Link führt",
    ),
    back="Zurück zum Inhalt",
    online="Dasselbe, online",
    document_title="Ein Dokument, das auf sich selbst verweist",
    over=(
        "Ein Link deckt diese Zeile ab",
        "und diese, und nichts dazwischen.",
    ),
    covered="Der Link oben deckt {n} Bereiche ab.",
    named="Zurück zum Inhalt, über ein benanntes Ziel",
    borders="Fünf Linkrahmen, jeder aus dem Link zurückgelesen:",
    styles=(
        "durchgezogen",
        "gestrichelt",
        "abgeschrägt",
        "vertieft",
        "unterstrichen",
    ),
    views="Zurück zum Inhalt, die Seite auf acht Arten gezeigt:",
    fits=(
        "ganze Seite",
        "volle Breite",
        "volle Höhe",
        "ein Rechteck",
        "ganze Zeichnung",
        "Breite der Zeichnung",
        "Höhe der Zeichnung",
        "fester Ort",
    ),
    flags="Jeder dieser Links trägt die Kennzeichen {bits}.",
    layer="Links",
    separator="Anderswo",
)

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

# The size the contents and the chapter titles are set at.
SIZE = 14.0


def contents_page(handle: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Page:
    """The contents: one clickable line per chapter, and an address that leaves."""
    content = hqf_pdf.Content()
    page = hqf_pdf.Page.a4()

    content.draw_text(handle, 20.0, 72.0, 760.0, words.contents)

    # A black line that is not a link, beside the blue lines that are.
    content.draw_text(handle, 10.0, 72.0, 735.0, words.what_is_clickable)

    top = 700.0
    for index, chapter in enumerate(words.chapters):
        line = f"{index + 1}. {chapter}"
        content.set_fill(hqf_pdf.Rgb(0.0, 0.2, 0.8))
        content.draw_text(handle, SIZE, 72.0, top, line)
        content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
        # Chapter one is the page after this one, which is index 1.
        page.add_link(
            hqf_pdf.Link.to_page(72.0, top - 3.0, handle.measure(line, SIZE), SIZE, index + 1)
        )
        top -= SIZE * 2.0

    content.set_fill(hqf_pdf.Rgb(0.0, 0.2, 0.8))
    content.draw_text(handle, SIZE, 72.0, top - 20.0, ADDRESS)
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    page.add_link(
        hqf_pdf.Link.to_uri(72.0, top - 23.0, handle.measure(ADDRESS, SIZE), SIZE, ADDRESS)
    )

    page.set_content(content)
    return page


def fits() -> list[hqf_pdf.PageFit]:
    """What each link of the third chapter's page shows the contents page as."""
    return [
        hqf_pdf.PageFit.whole_page(),
        hqf_pdf.PageFit.full_width(780.0),
        hqf_pdf.PageFit.full_height(72.0),
        hqf_pdf.PageFit.rectangle(hqf_pdf.Rect(72.0, 600.0, 300.0, 180.0)),
        hqf_pdf.PageFit.whole_drawing(),
        hqf_pdf.PageFit.drawing_width(780.0),
        hqf_pdf.PageFit.drawing_height(72.0),
        hqf_pdf.PageFit.fixed(left=72.0, top=780.0, zoom=2.0),
    ]


def style_name(words: Words, style) -> str:
    """The words a link's border is described by, from the style it reads back."""
    styles = (
        hqf_pdf.BorderStyle.Solid,
        hqf_pdf.BorderStyle.Dashed,
        hqf_pdf.BorderStyle.Beveled,
        hqf_pdf.BorderStyle.Inset,
        hqf_pdf.BorderStyle.Underline,
    )
    for known, name in zip(styles, words.styles):
        if style == known:
            return name
    return words.styles[0]


@dataclass(frozen=True)
class Shown:
    """What the chapter pages share: the layer their bordered links sit on, and the
    flags their shown links carry."""

    # The layer the bordered links of the second chapter belong to.
    layer: hqf_pdf.LayerHandle
    # The flags every link of the third chapter carries.
    flags: hqf_pdf.AnnotationFlags


def chapter_links(content, page, handle, words, index, shown) -> None:
    """What each chapter's page shows under its title: one link over two lines and
    one to a name, five borders, or eight ways of showing the contents."""
    blue = hqf_pdf.Rgb(0.0, 0.2, 0.8)
    if index == 0:
        content.set_fill(blue)
        content.draw_text(handle, SIZE, 72.0, 640.0, words.over[0])
        content.draw_text(handle, SIZE, 72.0, 620.0, words.over[1])
        content.draw_text(handle, SIZE, 72.0, 560.0, words.named)
        content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
        first = handle.measure(words.over[0], SIZE)
        second = handle.measure(words.over[1], SIZE)
        link = (
            hqf_pdf.Link.to_page(72.0, 617.0, max(first, second), 37.0, 0)
            .over(
                [
                    hqf_pdf.Rect(72.0, 637.0, first, SIZE).quad(),
                    hqf_pdf.Rect(72.0, 617.0, second, SIZE).quad(),
                ]
            )
            .description(words.back)
        )
        covered = len(link.areas)
        page.add_link(link)
        content.draw_text(
            handle, 9.0, 72.0, 600.0, words.covered.replace("{n}", str(covered))
        )
        page.add_link(
            hqf_pdf.Link.to_destination(
                72.0, 557.0, handle.measure(words.named, SIZE), SIZE, "contents"
            )
        )
    elif index == 1:
        content.draw_text(handle, SIZE, 72.0, 650.0, words.borders)
        dash = hqf_pdf.Dash.on_off(3.0, 2.0)
        borders = (
            (hqf_pdf.LinkBorder.solid(blue, 1.0), hqf_pdf.PressHighlight.None_),
            (hqf_pdf.LinkBorder.dashed(blue, 1.0, dash), hqf_pdf.PressHighlight.Invert),
            (hqf_pdf.LinkBorder.beveled(blue, 2.0), hqf_pdf.PressHighlight.Outline),
            (hqf_pdf.LinkBorder.inset(blue, 2.0), hqf_pdf.PressHighlight.Push),
            (hqf_pdf.LinkBorder.underline(blue, 1.5), hqf_pdf.PressHighlight.Invert),
        )
        top = 620.0
        for border, highlight in borders:
            lengths = (
                []
                if border.dash is None
                else [f"{length:.0f}" for length in border.dash.lengths]
            )
            pattern = f" [{' '.join(lengths)}]" if lengths else ""
            values = " ".join(f"{value:.1f}" for value in border.color.to_components())
            line = (
                f"{style_name(words, border.style)}, {border.width:g} pt{pattern}, "
                f"{values}"
            )
            content.draw_text(handle, 10.0, 80.0, top, line)
            page.add_link(
                hqf_pdf.Link.to_page(72.0, top - 6.0, 300.0, 20.0, 0)
                .border(border)
                .highlight(highlight)
                .layer(shown.layer)
            )
            top -= 30.0
    else:
        content.draw_text(handle, SIZE, 72.0, 650.0, words.views)
        top = 620.0
        for view, fit in zip(fits(), words.fits):
            content.set_fill(blue)
            content.draw_text(handle, 10.0, 80.0, top, fit)
            content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
            page.add_link(
                hqf_pdf.Link.to_page(72.0, top - 4.0, 200.0, 16.0, 0)
                .view(view)
                .flags(shown.flags)
            )
            top -= 24.0
        line = words.flags.replace("{bits}", str(shown.flags.bits))
        content.draw_text(handle, 9.0, 72.0, top - 10.0, line)
        # A link nobody sees, printed nowhere and never shown, which reading software
        # still lists.
        page.add_link(
            hqf_pdf.Link.to_page(500.0, 40.0, 20.0, 20.0, 0).flags(
                hqf_pdf.AnnotationFlags.none()
                .invisible()
                .hidden()
                .no_view()
                .toggle_no_view()
            )
        )


def chapter_page(
    handle: hqf_pdf.FontHandle, words: Words, index: int, shown: Shown
) -> hqf_pdf.Page:
    """A chapter page, with a line leading back to the contents."""
    content = hqf_pdf.Content()
    page = hqf_pdf.Page.a4()

    content.draw_text(handle, 20.0, 72.0, 760.0, f"{index + 1}. {words.chapters[index]}")

    content.set_fill(hqf_pdf.Rgb(0.0, 0.2, 0.8))
    content.draw_text(handle, SIZE, 72.0, 700.0, words.back)
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    page.add_link(
        hqf_pdf.Link.to_page(72.0, 697.0, handle.measure(words.back, SIZE), SIZE, 0)
    )
    chapter_links(content, page, handle, words, index, shown)

    page.set_content(content)
    return page


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", words.document_title)

    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    document.add_page(contents_page(handle, words))
    shown = Shown(
        layer=document.add_layer(hqf_pdf.Layer(words.layer)),
        flags=hqf_pdf.AnnotationFlags.from_bits(4)
        .no_zoom()
        .no_rotate()
        .read_only()
        .locked()
        .locked_contents(),
    )
    for index in range(len(words.chapters)):
        document.add_page(chapter_page(handle, words, index, shown))
    document.add_destination("contents", 0, hqf_pdf.PageFit.full_width(780.0))

    # The same contents again, as the panel a reader navigates by: the first chapter set
    # before the others once they are listed, a line that only separates, and the row to
    # the named contents in bold blue italics.
    document.add_bookmark(
        hqf_pdf.Bookmark(
            words.contents,
            0,
            children=[
                hqf_pdf.Bookmark(f"{index + 1}. {chapter}", index + 1).view(
                    hqf_pdf.PageFit.full_width(780.0)
                )
                for index, chapter in enumerate(words.chapters)
                if index > 0
            ],
            is_open=True,
        ).child_at(
            0,
            hqf_pdf.Bookmark(f"1. {words.chapters[0]}", 1).view(
                hqf_pdf.PageFit.whole_page()
            ),
        )
    )
    document.add_bookmark(hqf_pdf.Bookmark.separator(words.separator))
    document.add_bookmark(
        hqf_pdf.Bookmark.named(words.named, "contents")
        .color(hqf_pdf.Rgb(0.0, 0.2, 0.8))
        .bold()
        .italic()
    )
    document.add_bookmark(
        hqf_pdf.Bookmark.acting(words.online, hqf_pdf.Action.to_uri(ADDRESS))
    )

    written = document.write(out)
    print(f"wrote {out} ({written} bytes)")


if __name__ == "__main__":
    main()
