"""A slideshow: fourteen pages, each arriving by a different effect.

The Python twin of the `write_slideshow` example in Rust. The file opens full screen,
and every page states how it arrives and how long it stands before the next one comes by
itself. Nothing here is drawn by the effect: each page simply names the one that brings
it in, so what reading software does can be checked against what the file asked for.

The slides are written in the language `HQF_PDF_LANG` names: what an effect is called
and what it does are words a person reads. The entries the file writes for it are not
— `/S /Split /Dm /V /M /O` is what reading software parses, and it is the same in every
language, so each slide carries both.

The title slide also carries a link that acts rather than leads: following it asks
reading software to show the screen again, brought in by dissolving. Each slide keeps
the effect it states for itself.

Once out of full screen the file shows one page at a time with the thumbnails beside it,
and printing leaves the scaling to the reader.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# A slide, laid down sideways: a projected page is wider than it is tall.
SHEET = (720.0, 540.0)

# How far in from the edge of the slide everything is set.
MARGIN = 64.0

# How long each slide stands before the next arrives, in seconds.
STANDS = 4.0

# How long each effect takes, in seconds.
TAKES = 1.0

# The size a slide's name is set at, in points.
NAME = 54.0

# The size the line under a slide's name is set at, in points.
DOES = 15.0

# The size the title slide's heading is set at, in points.
TITLE = 42.0

# The size the lines of the title slide are set at, in points.
INTRO = 12.0

# How far apart the lines of the title slide are stacked, in points.
INTRO_STEP = 20.0

# The baseline of the line on the title slide that a link lies over.
FOLLOW_AT = 90.0

# How far below its baseline, and how far above, the link over that line reaches.
FOLLOW_REACH = (4.0, 12.0)

# How wide the link over that line is: the room between the two margins.
FOLLOW_WIDTH = SHEET[0] - 2.0 * MARGIN


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

    What is not language stays out of it: the entries the file writes for each effect
    are what reading software parses, and the name on the footer is a name.
    """

    # What the title slide is headed by.
    title: str
    # The line under that heading.
    strapline: str
    # What the title slide says the file asks reading software for.
    intro: tuple[str, str, str, str]
    # What the title slide says of itself.
    stands_still: str
    # The line on the title slide a link lies over, saying what following it does.
    follow: str
    # What stands between a slide's number and the count of them.
    of: str
    # What is written over the entries the file states for a slide.
    states_label: str
    # What each effect is called, in the order `effects` sets them.
    names: tuple[str, ...]
    # What each effect does, in the same order.
    does: tuple[str, ...]


# The slides in English.
ENGLISH = Words(
    title="Twelve ways in",
    strapline="Every effect a PDF can ask reading software for, one to a slide.",
    intro=(
        "This file opens full screen, and each slide states how it arrives and how "
        "long",
        "it stands before the next one comes by itself. Reading software that honours",
        "all of it runs the whole thing unattended; one that honours none of it shows",
        "fourteen pages, and nothing is lost.",
    ),
    stands_still=(
        "This first slide arrives by nothing at all: it is the one already on "
        "the screen."
    ),
    follow="Click this line and the screen you are on is shown again, dissolving in.",
    of="of",
    states_label="the file states",
    names=(
        "Split",
        "Blinds",
        "Box",
        "Wipe",
        "Dissolve",
        "Glitter",
        "Fly",
        "Fly, at the reader",
        "Push",
        "Cover",
        "Uncover",
        "Fade",
        "Replace",
    ),
    does=(
        "Two lines sweep apart to reveal the slide.",
        "Many lines sweep across at once, like a blind opening.",
        "A rectangle closes in on the middle of the slide.",
        "One line sweeps left to right.",
        "The slide before it dissolves into this one.",
        "The dissolve travels from the top-left corner down.",
        "The slide before it flies off downwards.",
        "What has changed flies out of the screen, starting small.",
        "Both slides slide together, the old one pushing this on.",
        "This slide slides up over the one before it.",
        "The slide before it slides down off this one.",
        "The slide fades up out of reading software's own background.",
        "Nothing sweeps or fades: the slide is simply there.",
    ),
)

# The slides in French.
FRENCH = Words(
    title="Douze façons d’entrer",
    strapline=(
        (("Tous les effets qu’un PDF demande au logiciel de lecture, un par "
          "diapositive."))
    ),
    intro=(
        ("Ce fichier s’ouvre en plein écran, et chaque diapositive indique comment "
         "elle arrive et"),
        ("combien de temps elle reste avant que la suivante vienne d’elle-même. Un "
         "logiciel"),
        ("de lecture qui respecte tout cela déroule l’ensemble tout seul ; celui qui "
         "n’en respecte"),
        "rien affiche quatorze pages, et rien n’est perdu.",
    ),
    stands_still=(
        ("Cette première diapositive n’arrive par aucun effet : c’est celle qui est "
         "déjà à l’écran.")
    ),
    follow=("Cliquez sur cette ligne : l’écran actuel s’affiche de nouveau, en "
            "dissolution."),
    of="sur",
    states_label="ce que le fichier écrit",
    names=(
        "Séparation",
        "Stores",
        "Boîte",
        "Balayage",
        "Dissolution",
        "Scintillement",
        "Envol",
        "Envol vers l’avant",
        "Poussée",
        "Recouvrement",
        "Dévoilement",
        "Fondu",
        "Remplacement",
    ),
    does=(
        "Deux traits s’écartent et découvrent la diapositive.",
        "Plusieurs traits balaient l’écran d’un coup, comme un store qui s’ouvre.",
        "Un rectangle se referme sur le milieu de la diapositive.",
        "Un trait balaie l’écran de la gauche vers la droite.",
        "La diapositive précédente se dissout dans celle-ci.",
        "La dissolution part du coin supérieur gauche et descend.",
        "La diapositive précédente file vers le bas et sort de l’écran.",
        "Ce qui a changé surgit de l’écran, d’abord petit puis grand.",
        "Les deux diapositives glissent ensemble, l’ancienne poussant celle-ci.",
        "Cette diapositive glisse vers le haut par-dessus la précédente.",
        "La diapositive précédente glisse vers le bas et libère celle-ci.",
        "La diapositive apparaît en fondu depuis le fond du logiciel de lecture.",
        "Rien ne balaie ni ne s’estompe : la diapositive est simplement là.",
    ),
)

# The slides in Dutch.
DUTCH = Words(
    title="Twaalf ingangen",
    strapline="Elk effect dat een pdf aan leessoftware kan vragen, één per dia.",
    intro=(
        "Dit bestand opent op volledig scherm, en elke dia zegt hoe ze binnenkomt en "
        "hoe lang",
        "ze blijft staan voordat de volgende vanzelf komt. Leessoftware die alles",
        "respecteert, speelt het geheel zonder toezicht af; software die niets respecteert, toont",
        "veertien pagina’s, en er gaat niets verloren.",
    ),
    stands_still=(
        "Deze eerste dia komt op geen enkele manier binnen: ze staat al op het scherm."
    ),
    follow="Klik op deze regel en het huidige scherm wordt opnieuw getoond, invloeiend.",
    of="van",
    states_label="het bestand noemt",
    names=(
        "Splitsen",
        "Jaloezieën",
        "Kader",
        "Vegen",
        "Oplossen",
        "Glinsteren",
        "Vliegen",
        "Vliegen naar de lezer",
        "Duwen",
        "Bedekken",
        "Onthullen",
        "Vervagen",
        "Vervangen",
    ),
    does=(
        "Twee lijnen schuiven uiteen om de dia te onthullen.",
        "Veel lijnen vegen tegelijk, als een jaloezie die opengaat.",
        "Een rechthoek sluit zich naar het midden van de dia.",
        "Eén lijn veegt van links naar rechts.",
        "De vorige dia lost op in deze.",
        "Het oplossen loopt van de linkerbovenhoek naar beneden.",
        "De vorige dia vliegt naar beneden weg.",
        "Wat veranderd is, vliegt het scherm uit, klein beginnend.",
        "Beide dia’s schuiven samen, de oude door deze weggeduwd.",
        "Deze dia schuift omhoog over de vorige.",
        "De vorige dia schuift naar beneden van deze af.",
        "De dia verschijnt uit de eigen achtergrond van de leessoftware.",
        "Niets veegt of vervaagt: de dia is er gewoon.",
    ),
)

# The slides in Portuguese.
PORTUGUESE = Words(
    title="Doze formas de entrar",
    strapline="Cada efeito que um PDF pede a um programa de leitura, um por diapositivo.",
    intro=(
        "Este ficheiro abre em ecrã inteiro, e cada diapositivo indica como chega e "
        "quanto",
        "tempo fica antes de o seguinte vir sozinho. Um programa de leitura que respeite",
        "tudo passa-o inteiro sem que ninguém toque em nada; um que não respeite nada mostra",
        "catorze páginas, e não se perde nada.",
    ),
    stands_still=(
        "Este primeiro diapositivo não chega de forma nenhuma: é o que já está no "
        "ecrã."
    ),
    follow="Clique nesta linha e o ecrã atual volta a ser mostrado, a dissolver-se.",
    of="de",
    states_label="o ficheiro indica",
    names=(
        "Divisão",
        "Persianas",
        "Caixa",
        "Varrimento",
        "Dissolução",
        "Cintilação",
        "Voo",
        "Voo, para o leitor",
        "Empurrão",
        "Cobertura",
        "Revelação",
        "Desvanecimento",
        "Substituição",
    ),
    does=(
        "Duas linhas afastam-se para revelar o diapositivo.",
        "Muitas linhas varrem ao mesmo tempo, como uma persiana a abrir.",
        "Um retângulo fecha-se para o meio do diapositivo.",
        "Uma linha varre da esquerda para a direita.",
        "O diapositivo anterior dissolve-se neste.",
        "A dissolução avança do canto superior esquerdo para baixo.",
        "O diapositivo anterior voa para baixo.",
        "O que mudou voa para fora do ecrã, a começar pequeno.",
        "Os dois diapositivos deslizam juntos, o antigo empurrado por este.",
        "Este diapositivo sobe a deslizar por cima do anterior.",
        "O diapositivo anterior desce a deslizar e deixa ver este.",
        "O diapositivo surge a partir do fundo próprio do programa de leitura.",
        "Nada varre nem desvanece: o diapositivo simplesmente está lá.",
    ),
)

# The slides in Italian.
ITALIAN = Words(
    title="Dodici modi di entrare",
    strapline="Ogni effetto che un PDF chiede al programma di lettura, uno a diapositiva.",
    intro=(
        "Questo file si apre a schermo intero, e ogni diapositiva indica come arriva "
        "e quanto",
        "resta prima che la successiva arrivi da sola. Un programma di lettura che rispetta",
        "tutto lo fa scorrere da sé; uno che non rispetta nulla mostra",
        "quattordici pagine, e non si perde niente.",
    ),
    stands_still=(
        "Questa prima diapositiva non arriva in alcun modo: è quella già sullo "
        "schermo."
    ),
    follow="Cliccate su questa riga e lo schermo attuale si mostra di nuovo, dissolvendosi.",
    of="di",
    states_label="il file indica",
    names=(
        "Divisione",
        "Veneziane",
        "Riquadro",
        "Tendina",
        "Dissolvenza",
        "Scintillio",
        "Volo",
        "Volo, verso il lettore",
        "Spinta",
        "Copertura",
        "Scopertura",
        "Sfumatura",
        "Sostituzione",
    ),
    does=(
        "Due linee si separano per scoprire la diapositiva.",
        "Molte linee scorrono insieme, come una veneziana che si apre.",
        "Un rettangolo si stringe verso il centro della diapositiva.",
        "Una linea scorre da sinistra a destra.",
        "La diapositiva precedente si dissolve in questa.",
        "La dissolvenza procede dall’angolo in alto a sinistra verso il basso.",
        "La diapositiva precedente vola via verso il basso.",
        "Ciò che è cambiato vola fuori dallo schermo, partendo piccolo.",
        "Le due diapositive scorrono insieme, la vecchia spinta da questa.",
        "Questa diapositiva sale scorrendo sopra la precedente.",
        "La diapositiva precedente scende scorrendo e scopre questa.",
        "La diapositiva sfuma dallo sfondo proprio del programma di lettura.",
        "Niente scorre né sfuma: la diapositiva è semplicemente lì.",
    ),
)

# The slides in Spanish.
SPANISH = Words(
    title="Doce formas de entrar",
    strapline="Cada efecto que un PDF pide a un programa de lectura, uno por diapositiva.",
    intro=(
        "Este archivo se abre a pantalla completa, y cada diapositiva indica cómo "
        "llega y cuánto",
        "tiempo se queda antes de que la siguiente venga sola. Un programa de lectura que lo respeta",
        "todo lo pasa entero sin que nadie toque nada; uno que no respeta nada muestra",
        "catorce páginas, y no se pierde nada.",
    ),
    stands_still=(
        "Esta primera diapositiva no llega de ninguna forma: es la que ya está en "
        "pantalla."
    ),
    follow="Haga clic en esta línea y la pantalla actual se vuelve a mostrar, fundiéndose.",
    of="de",
    states_label="el archivo indica",
    names=(
        "División",
        "Persianas",
        "Caja",
        "Barrido",
        "Disolución",
        "Destellos",
        "Vuelo",
        "Vuelo, hacia el lector",
        "Empuje",
        "Cubrir",
        "Descubrir",
        "Fundido",
        "Reemplazo",
    ),
    does=(
        "Dos líneas se separan para descubrir la diapositiva.",
        "Muchas líneas barren a la vez, como una persiana que se abre.",
        "Un rectángulo se cierra hacia el centro de la diapositiva.",
        "Una línea barre de izquierda a derecha.",
        "La diapositiva anterior se disuelve en esta.",
        "La disolución avanza desde la esquina superior izquierda hacia abajo.",
        "La diapositiva anterior sale volando hacia abajo.",
        "Lo que ha cambiado sale volando de la pantalla, empezando pequeño.",
        "Las dos diapositivas se deslizan juntas, la anterior empujando a esta.",
        "Esta diapositiva sube deslizándose sobre la anterior.",
        "La diapositiva anterior baja deslizándose y deja ver esta.",
        "La diapositiva aparece desde el fondo propio del programa de lectura.",
        "Nada barre ni se funde: la diapositiva simplemente está.",
    ),
)

# The slides in German.
GERMAN = Words(
    title="Zwölf Auftritte",
    strapline="Jeder Effekt, den ein PDF verlangen kann, einer je Folie.",
    intro=(
        "Die Datei öffnet im Vollbild, und jede Folie sagt, wie sie erscheint und wie "
        "lange",
        "sie steht, bevor die nächste von selbst kommt. Eine Lesesoftware, die alles befolgt,",
        "spielt das Ganze unbeaufsichtigt ab; eine, die nichts davon befolgt, zeigt vierzehn",
        "Seiten, und nichts geht verloren.",
    ),
    stands_still=(
        "Diese erste Folie erscheint durch gar nichts: Sie ist schon auf dem "
        "Bildschirm."
    ),
    follow="Ein Klick auf diese Zeile zeigt den aktuellen Bildschirm erneut, eingeblendet.",
    of="von",
    states_label="die Datei gibt an",
    names=(
        "Teilen",
        "Jalousie",
        "Rechteck",
        "Wischen",
        "Auflösen",
        "Glitzern",
        "Fliegen",
        "Fliegen, zum Leser",
        "Schieben",
        "Überdecken",
        "Aufdecken",
        "Überblenden",
        "Ersetzen",
    ),
    does=(
        "Zwei Linien fahren auseinander und geben die Folie frei.",
        "Viele Linien fahren zugleich darüber, wie eine sich öffnende Jalousie.",
        "Ein Rechteck schließt sich zur Mitte der Folie hin.",
        "Eine Linie fährt von links nach rechts.",
        "Die vorige Folie löst sich in diese auf.",
        "Das Auflösen wandert von der linken oberen Ecke nach unten.",
        "Die vorige Folie fliegt nach unten weg.",
        "Was sich geändert hat, fliegt aus dem Bildschirm, klein beginnend.",
        "Beide Folien gleiten zusammen, die alte schiebt diese herein.",
        "Diese Folie gleitet von unten über die vorige.",
        "Die vorige Folie gleitet nach unten von dieser weg.",
        "Die Folie blendet aus dem eigenen Hintergrund der Lesesoftware auf.",
        "Nichts fährt oder blendet: Die Folie ist einfach da.",
    ),
)

# 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 slide(font, words, wash, number, name, does, states):
    """One slide: a wash of colour, the effect that brings it in, and its entries."""
    content = hqf_pdf.Content()
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(wash[0], wash[1], wash[2]))
    content.rect(0.0, 0.0, SHEET[0], SHEET[1])
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(1.0, 1.0, 1.0))
    content.rect(0.0, SHEET[1] - 8.0, SHEET[0], 8.0)
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(1.0, 1.0, 1.0))
    content.draw_text(font, DOES, MARGIN, SHEET[1] - 70.0, number)
    content.draw_text(font, NAME, MARGIN, 300.0, name)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.92))
    content.draw_text(font, DOES, MARGIN, 254.0, does)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.82))
    content.draw_text(font, 11.0, MARGIN, MARGIN + 34.0, words.states_label)
    content.draw_text(font, 11.0, MARGIN, MARGIN + 16.0, states)
    content.restore_state()
    return content


def title(font, words):
    """The title slide, which nothing brings in: it is the one already there."""
    content = hqf_pdf.Content()
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.09, 0.11, 0.16))
    content.rect(0.0, 0.0, SHEET[0], SHEET[1])
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(1.0, 1.0, 1.0))
    content.draw_text(font, TITLE, MARGIN, 330.0, words.title)
    content.set_fill(hqf_pdf.Color.gray(0.72))
    content.draw_text(font, DOES, MARGIN, 286.0, words.strapline)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.55))
    y = 210.0
    for line in words.intro:
        content.draw_text(font, INTRO, MARGIN, y, line)
        y -= INTRO_STEP

    # The line that speaks of this slide alone stands a blank line clear of the ones
    # that speak of the file.
    y -= INTRO_STEP
    content.draw_text(font, INTRO, MARGIN, y, words.stands_still)
    content.draw_text(font, INTRO, MARGIN, FOLLOW_AT, words.follow)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.4))
    content.draw_text(font, 11.0, MARGIN, MARGIN, "HQF Development")
    content.restore_state()
    return content


def effects():
    """The thirteen slides after the title one, one to an effect.

    The twelve effects the format defines, `Fly` standing on two of them. Each entry
    is how the slide arrives, the wash it is laid on, and the entries the file writes
    for it. What the effect is called and what it does are words a person reads, and
    are held in `Words`.
    """
    return [
        (
            hqf_pdf.Effect.split(hqf_pdf.Axis.Vertical, hqf_pdf.Motion.Outward),
            (0.13, 0.29, 0.36),
            "/S /Split /Dm /V /M /O",
        ),
        (
            hqf_pdf.Effect.blinds(hqf_pdf.Axis.Horizontal),
            (0.16, 0.34, 0.31),
            "/S /Blinds /Dm /H",
        ),
        (
            hqf_pdf.Effect.box(hqf_pdf.Motion.Inward),
            (0.24, 0.33, 0.22),
            "/S /Box /M /I",
        ),
        (
            hqf_pdf.Effect.wipe(hqf_pdf.Heading.Rightwards),
            (0.36, 0.32, 0.16),
            "/S /Wipe /Di 0",
        ),
        (
            hqf_pdf.Effect.dissolve(),
            (0.40, 0.26, 0.16),
            "/S /Dissolve",
        ),
        (
            hqf_pdf.Effect.glitter(hqf_pdf.Heading.Diagonally),
            (0.42, 0.20, 0.20),
            "/S /Glitter /Di 315",
        ),
        (
            hqf_pdf.Effect.fly(hqf_pdf.Heading.Downwards),
            (0.38, 0.17, 0.30),
            "/S /Fly /Di 270 /B true",
        ),
        (
            hqf_pdf.Effect.fly(None, 0.6, False),
            (0.31, 0.18, 0.38),
            "/S /Fly /Di /None /SS 0.6 /B false",
        ),
        (
            hqf_pdf.Effect.push(hqf_pdf.Heading.Leftwards),
            (0.21, 0.20, 0.42),
            "/S /Push /Di 180",
        ),
        (
            hqf_pdf.Effect.cover(hqf_pdf.Heading.Upwards),
            (0.14, 0.26, 0.42),
            "/S /Cover /Di 90",
        ),
        (
            hqf_pdf.Effect.uncover(hqf_pdf.Heading.Downwards),
            (0.11, 0.31, 0.38),
            "/S /Uncover /Di 270",
        ),
        (
            hqf_pdf.Effect.fade(),
            (0.20, 0.20, 0.22),
            "/S /Fade",
        ),
        (
            hqf_pdf.Effect.replace(),
            (0.09, 0.11, 0.16),
            "/S /R",
        ),
    ]


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

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

    first = hqf_pdf.Page(SHEET[0], SHEET[1])
    first.set_content(title(font, words))
    first.set_duration(STANDS)
    first.add_link(
        hqf_pdf.Link.acting(
            MARGIN,
            FOLLOW_AT - FOLLOW_REACH[0],
            FOLLOW_WIDTH,
            FOLLOW_REACH[0] + FOLLOW_REACH[1],
            hqf_pdf.Action.transition(
                hqf_pdf.Transition(hqf_pdf.Effect.dissolve()).seconds(TAKES)
            ),
        )
    )
    document.add_page(first)

    all_effects = effects()
    total = len(all_effects) + 1
    for index, (effect, wash, states) in enumerate(all_effects):
        number = f"{index + 2} {words.of} {total}"
        page = hqf_pdf.Page(SHEET[0], SHEET[1])
        page.set_content(
            slide(
                font,
                words,
                wash,
                number,
                words.names[index],
                words.does[index],
                states,
            )
        )
        page.set_transition(hqf_pdf.Transition(effect).seconds(TAKES))
        page.set_duration(STANDS)
        document.add_page(page)

    # A transition is read in full screen and nowhere else, so a slideshow that does not
    # ask for full screen asks for nothing.
    document.set_open_mode(hqf_pdf.OpenMode.FullScreen)

    document.set_page_layout(hqf_pdf.PageLayout.SinglePage)

    document.set_viewer_preferences(

        hqf_pdf.ViewerPreferences()

        .after_full_screen(hqf_pdf.SidePanel.Thumbnails)

        .print_scaling(hqf_pdf.PrintScaling.Viewer)

    )

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {document.page_count} slides, each "
        f"arriving by a different effect"
    )


if __name__ == "__main__":
    main()
