"""Fades, vignettes, cut-out and punched-out letters, all from soft masks.

The Python twin of the `write_soft_mask` example in Rust. A soft mask is a
drawing composited apart from the page and then read as a coverage rather than
shown: where it comes out light, what the state paints goes through whole; where
it comes out dark, nothing does. The same six panels are painted the same way —
one flat rectangle each — and differ only in the mask in force. The fifth is the
third's mask turned inside out. The sixth draws its letters dark on a white backdrop,
the colour the mask reads wherever its drawing paints nothing, and bends what it reads
through a curve, so the letters let the panel through at half strength.

The page is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. The two words the third mask is drawn in are language as much as the captions
are: they are what the panel is seen through, and what the fifth is punched out by.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The size of one panel, in points.
PANEL = (215.0, 100.0)

# The bottom-left corner of each panel.
CORNERS = [
    (70.0, 630.0),
    (305.0, 630.0),
    (70.0, 500.0),
    (305.0, 500.0),
    (70.0, 370.0),
    (305.0, 370.0),
]

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

    The two words the third mask is drawn in are here with the rest: the panel is seen
    through their shapes, so a reader reads them as much as a caption.
    """

    # The line at the head of the page.
    title: str
    # The two lines under it, saying what a mask is.
    intro: tuple[str, str]
    # What each panel shows, in the order they are laid out.
    captions: tuple[str, str, str, str, str, str]
    # The two words the third panel is cut through.
    cut: tuple[str, str]
    # The word on the tag the band's last state paints whole.
    whole: str
    # What stands under the band.
    band: str


# The page in English.
ENGLISH = Words(
    title="One flat rectangle, six masks",
    intro=(
        "Each panel below is the same rectangle in the same colour. What differs "
        "is the mask in",
        "force: a drawing composited apart from the page and read as a coverage "
        "rather than shown.",
    ),
    captions=(
        "Faded away by a black-to-white gradient",
        "Held in the middle by a radial one",
        "Cut through letters the mask drew",
        "Read from how opaque the mask came out",
        "Punched out by the same letters, turned inside out",
        "Letters on a white backdrop, eased by a curve",
    ),
    cut=("MASK", "THIS"),
    whole="WHOLE",
    band="A band running out under a mask, and a tag a second state paints whole",
)

# The page in French.
FRENCH = Words(
    title="Un rectangle plat, six masques",
    intro=(
        "Chaque panneau ci-dessous est le même rectangle, dans la même couleur. "
        "Seul change le",
        ("masque en vigueur : un dessin composé à part, lu comme une couverture, "
         "jamais affiché."),
    ),
    captions=(
        "Estompé par un dégradé du noir au blanc",
        "Retenu au centre par un dégradé radial",
        "Découpé par les lettres du masque",
        "Lu sur l’opacité du masque, non sur sa clarté",
        "Évidé par les mêmes lettres, masque inversé",
        "Lettres sur fond blanc, adoucies par une courbe",
    ),
    cut=("ÔTE", "ÇA"),
    whole="ENTIER",
    band=("Une bande qui s’éteint sous un masque, une étiquette qu’un second état "
          "peint entière"),
)

# The page in Dutch.
DUTCH = Words(
    title="Eén effen rechthoek, zes maskers",
    intro=(
        "Elk paneel hieronder is dezelfde rechthoek in dezelfde kleur. Wat verschilt "
        "is het masker dat",
        "geldt: een tekening die los van de pagina wordt samengesteld en als dekking "
        "gelezen in plaats van getoond.",
    ),
    captions=(
        "Weggevaagd door een verloop van zwart naar wit",
        "In het midden vastgehouden door een radiaal verloop",
        "Uitgesneden door letters die het masker tekende",
        "Gelezen uit hoe dekkend het masker uitviel",
        "Uitgestanst door dezelfde letters, binnenstebuiten",
        "Letters op een witte achtergrond, verzacht door een curve",
    ),
    cut=("MASKER", "DIT"),
    whole="HEEL",
    band="Een band die onder een masker uitloopt, en een label dat een tweede status helemaal schildert",
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Um retângulo liso, seis máscaras",
    intro=(
        "Cada painel abaixo é o mesmo retângulo na mesma cor. O que muda é a máscara",
        "em vigor: um desenho composto à parte da página e lido como cobertura em vez "
        "de ser mostrado.",
    ),
    captions=(
        "Esbatido por um degradé do preto ao branco",
        "Preso ao meio por um radial",
        "Recortado através de letras que a máscara desenhou",
        "Lido pela opacidade com que a máscara saiu",
        "Perfurado pelas mesmas letras, do avesso",
        "Letras sobre fundo branco, suavizadas por uma curva",
    ),
    cut=("MÁSCARA", "ESTE"),
    whole="INTEIRO",
    band="Uma faixa que se apaga sob uma máscara, e uma etiqueta que um segundo estado pinta inteira",
)

# The page in Italian.
ITALIAN = Words(
    title="Un rettangolo piatto, sei maschere",
    intro=(
        "Ogni pannello qui sotto è lo stesso rettangolo dello stesso colore. Ciò che "
        "cambia è la maschera",
        "in vigore: un disegno composto a parte dalla pagina e letto come copertura "
        "anziché mostrato.",
    ),
    captions=(
        "Sfumato da un gradiente dal nero al bianco",
        "Tenuto al centro da uno radiale",
        "Ritagliato attraverso lettere disegnate dalla maschera",
        "Letto da quanto opaca è uscita la maschera",
        "Traforato dalle stesse lettere, rovesciate",
        "Lettere su fondo bianco, ammorbidite da una curva",
    ),
    cut=("MASCHERA", "QUESTO"),
    whole="INTERO",
    band="Una fascia che si spegne sotto una maschera, e un’etichetta che un secondo stato dipinge intera",
)

# The page in Spanish.
SPANISH = Words(
    title="Un rectángulo plano, seis máscaras",
    intro=(
        "Cada panel de abajo es el mismo rectángulo del mismo color. Lo que cambia es "
        "la máscara",
        "vigente: un dibujo compuesto aparte de la página y leído como cobertura en "
        "vez de mostrarse.",
    ),
    captions=(
        "Desvanecido por un degradado de negro a blanco",
        "Sostenido en el centro por uno radial",
        "Recortado a través de letras que dibujó la máscara",
        "Leído según lo opaca que salió la máscara",
        "Perforado por las mismas letras, del revés",
        "Letras sobre un fondo blanco, suavizadas por una curva",
    ),
    cut=("MÁSCARA", "ESTE"),
    whole="ENTERO",
    band="Una banda que se apaga bajo una máscara, y una etiqueta que un segundo estado pinta entera",
)

# The page in German.
GERMAN = Words(
    title="Ein flaches Rechteck, sechs Masken",
    intro=(
        "Jedes Feld unten ist dasselbe Rechteck in derselben Farbe. Was sich "
        "unterscheidet, ist die",
        "wirksame Maske: eine getrennt von der Seite zusammengesetzte Zeichnung, als "
        "Deckung gelesen.",
    ),
    captions=(
        "Durch einen Verlauf von Schwarz nach Weiß ausgeblendet",
        "Durch einen radialen Verlauf in der Mitte gehalten",
        "Durch Buchstaben geschnitten, die die Maske zeichnete",
        "Aus der Deckkraft gelesen, mit der die Maske herauskam",
        "Von denselben Buchstaben ausgestanzt, umgekehrt",
        "Buchstaben auf weißem Hintergrund, durch eine Kurve gemildert",
    ),
    cut=("MASKE", "DIESE"),
    whole="GANZ",
    band="Ein Band, das unter einer Maske ausläuft, und ein Etikett, das ein zweiter Zustand ganz malt",
)


# 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 box_of(corner: tuple[float, float]) -> tuple[float, float, float, float]:
    """The rectangle of the panel at `corner`, as a quadruple."""
    width, height = PANEL
    return (corner[0], corner[1], width, height)


def painted_group(
    content: hqf_pdf.Content,
    corner: tuple[float, float],
    shading: hqf_pdf.ShadingHandle,
) -> None:
    """Paints `shading` across the panel at `corner` and nothing outside it."""
    x, y, width, height = box_of(corner)
    content.save_state()
    content.rect(x, y, width, height)
    content.clip()
    content.end_path()
    content.draw_shading(shading)
    content.restore_state()


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

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

    black = hqf_pdf.Rgb.gray(0.0)
    white = hqf_pdf.Rgb.gray(1.0)

    # The mask of the first panel: a gradient running the panel's width, dark at the
    # left and light at the right.
    x0, y0, width0, _ = box_of(CORNERS[0])
    sweep = document.add_shading(
        hqf_pdf.Axial.rgb((x0, y0), (x0 + width0, y0), black, white)
    )
    faded = hqf_pdf.Content()
    painted_group(faded, CORNERS[0], sweep)
    fade = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(faded, hqf_pdf.Rect(x0, y0, width0, PANEL[1])),
                hqf_pdf.DeviceSpace.Rgb,
            )
        )
    )

    # The second: light in the middle of the panel and dark at its edge, so what it
    # masks is held in the middle and let go at the sides.
    x1, y1, width1, height1 = box_of(CORNERS[1])
    middle = (x1 + width1 / 2.0, y1 + height1 / 2.0)
    halo = document.add_shading(
        hqf_pdf.Radial.rgb(
            (middle[0], middle[1], 0.0),
            (middle[0], middle[1], height1 / 2.0),
            white,
            black,
        ).extend(False, True)
    )
    vignette = hqf_pdf.Content()
    painted_group(vignette, CORNERS[1], halo)
    hold = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(
                    vignette, hqf_pdf.Rect(x1, y1, width1, height1)
                ),
                hqf_pdf.DeviceSpace.Rgb,
            )
        )
    )

    # The third: letters in white on nothing at all. Everything the mask left alone
    # stays black, which lets nothing through, so the panel is seen only through the
    # shapes of the letters.
    x2, y2, width2, height2 = box_of(CORNERS[2])
    letters = hqf_pdf.Content()
    letters.set_fill(white)
    letters.draw_text(font, 38.0, x2 + 12.0, y2 + 56.0, words.cut[0])
    letters.draw_text(font, 38.0, x2 + 12.0, y2 + 14.0, words.cut[1])
    cut = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(letters, hqf_pdf.Rect(x2, y2, width2, height2)),
                hqf_pdf.DeviceSpace.Rgb,
            )
        )
    )

    # The fifth: the same letters, and the mask turned inside out, so the letters stop
    # the panel and everything round them lets it through.
    x4, y4, width4, height4 = box_of(CORNERS[4])
    punched = hqf_pdf.Content()
    punched.set_fill(white)
    punched.draw_text(font, 38.0, x4 + 12.0, y4 + 56.0, words.cut[0])
    punched.draw_text(font, 38.0, x4 + 12.0, y4 + 14.0, words.cut[1])
    punch = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(punched, hqf_pdf.Rect(x4, y4, width4, height4)),
                hqf_pdf.DeviceSpace.Rgb,
            ).inverted()
        )
    )

    # The fourth reads how opaque the mask came out rather than how light, so the shapes
    # it paints let the panel through by exactly the opacity they were painted at,
    # whatever colour they were.
    dimmed = document.add_ext_gstate(hqf_pdf.ExtGState(fill_alpha=0.4, stroke_alpha=0.4))
    x3, y3, width3, height3 = box_of(CORNERS[3])
    shapes = hqf_pdf.Content()
    shapes.set_fill(hqf_pdf.Rgb(0.2, 0.6, 0.9))
    shapes.rect(x3 + 14.0, y3 + 14.0, 90.0, 72.0)
    shapes.fill()
    shapes.save_state()
    shapes.set_ext_gstate(dimmed)
    shapes.set_fill(hqf_pdf.Rgb(0.9, 0.4, 0.1))
    shapes.rect(x3 + 112.0, y3 + 14.0, 90.0, 72.0)
    shapes.fill()
    shapes.restore_state()
    through = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.alpha(
                hqf_pdf.Drawing(shapes, hqf_pdf.Rect(x3, y3, width3, height3))
            )
        )
    )

    # The sixth: the letters drawn dark, on a backdrop of white. Where the drawing
    # paints nothing the mask reads the backdrop and lets the panel through; the curve
    # lifts the dark of the letters halfway, so they let half of it through.
    x5, y5, width5, height5 = box_of(CORNERS[5])
    dark = hqf_pdf.Content()
    dark.set_fill(black)
    dark.draw_text(font, 38.0, x5 + 12.0, y5 + 56.0, words.cut[0])
    dark.draw_text(font, 38.0, x5 + 12.0, y5 + 14.0, words.cut[1])
    eased = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(dark, hqf_pdf.Rect(x5, y5, width5, height5)),
                hqf_pdf.DeviceSpace.Rgb,
            )
            .backdrop([1.0, 1.0, 1.0])
            .transfer(
                hqf_pdf.Function.exponential((0.0, 1.0), 1.0, endpoints=([0.5], [1.0]))
            )
        )
    )

    # The last: a band running out towards its right edge, and the state that drops the
    # mask again for what is painted inside it.
    run_out = document.add_shading(
        hqf_pdf.Axial.rgb((70.0, 200.0), (520.0, 200.0), white, black)
    )
    band = hqf_pdf.Content()
    band.save_state()
    band.rect(70.0, 200.0, 450.0, 130.0)
    band.clip()
    band.end_path()
    band.draw_shading(run_out)
    band.restore_state()
    run_out = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(band, hqf_pdf.Rect(70.0, 200.0, 450.0, 130.0)),
                hqf_pdf.DeviceSpace.Rgb,
            )
        )
    )
    whole = document.add_ext_gstate(hqf_pdf.ExtGState(without_soft_mask=True))

    content = hqf_pdf.Content()
    content.draw_text(font, 15.0, 70.0, 780.0, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        70.0,
        762.0,
        words.intro[0],
    )
    content.draw_text(
        font,
        10.0,
        70.0,
        748.0,
        words.intro[1],
    )
    content.restore_state()

    ink = hqf_pdf.Rgb(0.12, 0.28, 0.52)
    states = [fade, hold, cut, through, punch, eased]
    for corner, caption, state in zip(CORNERS, words.captions, states):
        x, y, width, height = box_of(corner)

        content.save_state()
        content.set_fill(hqf_pdf.Rgb(0.96, 0.96, 0.94))
        content.rect(x, y, width, height)
        content.fill()
        content.set_ext_gstate(state)
        content.set_fill(ink)
        content.rect(x, y, width, height)
        content.fill()
        content.restore_state()

        content.save_state()
        content.set_stroke(hqf_pdf.Rgb.gray(0.55))
        content.set_line_width(0.6)
        content.rect(x, y, width, height)
        content.stroke()
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        content.draw_text(font, 9.0, x, y - 14.0, caption)
        content.restore_state()

    # A mask holds until the state that set it is restored, or until a state drops it:
    # the band fades out, and the tag inside it is painted whole.
    x4, y4 = 70.0, 200.0
    width4, height4 = 450.0, 130.0
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.96, 0.96, 0.94))
    content.rect(x4, y4, width4, height4)
    content.fill()
    content.set_ext_gstate(run_out)
    content.set_fill(ink)
    content.rect(x4, y4, width4, height4)
    content.fill()

    content.save_state()
    content.set_ext_gstate(whole)
    content.set_fill(hqf_pdf.Rgb(0.85, 0.42, 0.15))
    content.rect(x4 + 300.0, y4 + 45.0, 120.0, 60.0)
    content.fill()
    content.set_fill(hqf_pdf.Rgb.gray(1.0))
    content.draw_text(font, 13.0, x4 + 318.0, y4 + 68.0, words.whole)
    content.restore_state()
    content.restore_state()

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.55))
    content.set_line_width(0.6)
    content.rect(x4, y4, width4, height4)
    content.stroke()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        9.0,
        x4,
        y4 - 14.0,
        words.band,
    )
    content.restore_state()

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

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {len(CORNERS)} masked panels "
        "and a band that runs out"
    )


if __name__ == "__main__":
    main()
