"""A slideshow: twelve 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 a reader 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 a reader parses, and it is the same in every
language, so each slide carries both.

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


@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 a reader 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 a reader for.
    intro: tuple[str, str, str, str]
    # What the title slide says of itself.
    stands_still: 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 a reader 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. A reader that honours all "
        "of it runs",
        "the whole thing unattended; one that honours none of it shows thirteen "
        "pages, and",
        "nothing is lost.",
    ),
    stands_still=(
        "This first slide arrives by nothing at all: it is the one already on "
        "the screen."
    ),
    of="of",
    states_label="the file states",
    names=(
        "Split",
        "Blinds",
        "Box",
        "Wipe",
        "Dissolve",
        "Glitter",
        "Fly",
        "Fly, at the reader",
        "Push",
        "Cover",
        "Uncover",
        "Fade",
    ),
    does=(
        "Two lines sweep apart to reveal the slide.",
        "Many lines sweep across at once, like a blind opening.",
        "A rectangle opens out of 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 the reader's own background.",
    ),
)

# The slides in French.
FRENCH = Words(
    title="Douze façons d'entrer",
    strapline=(
        "Tous les effets qu'un PDF peut demander à un lecteur, un par diapositive."
    ),
    intro=(
        "Ce fichier s'ouvre en plein écran, et chaque diapositive dit comment "
        "elle arrive et",
        "combien de temps elle reste avant que la suivante vienne d'elle-même. "
        "Un lecteur qui",
        "suit tout cela déroule l'ensemble sans personne ; celui qui n'en suit "
        "rien montre",
        "treize pages, et rien n'est perdu.",
    ),
    stands_still=(
        "Cette première diapositive n'arrive par rien du tout : elle est déjà à "
        "l'écran."
    ),
    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",
    ),
    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 s'ouvre depuis 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 haut gauche et descend.",
        "La diapositive précédente s'envole vers le bas.",
        "Ce qui a changé sort de l'écran, petit d'abord 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 lecteur.",
    ),
)

# 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 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.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 twelve effects, one to a slide.

    Each 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.Outward),
            (0.24, 0.33, 0.22),
            "/S /Box /M /O",
        ),
        (
            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",
        ),
    ]


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

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