"""Fades, vignettes and cut-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 four panels are painted the same way —
one flat rectangle each — and differ only in the mask in force.

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.

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

# The bottom-left corner of each panel.
CORNERS = [
    (70.0, 560.0),
    (305.0, 560.0),
    (70.0, 380.0),
    (305.0, 380.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]
    # 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, four 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",
    ),
    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, quatre 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 de la page et lu comme une "
        "couverture.",
    ),
    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, pas sa clarté",
    ),
    cut=("ÔTE", "ÇA"),
    whole="ENTIER",
    band="Une bande qui s'éteint sous un masque, et une étiquette peinte entière",
)


# 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 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, 44.0, x2 + 12.0, y2 + 84.0, words.cut[0])
    letters.draw_text(font, 44.0, x2 + 12.0, y2 + 34.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 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, 122.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, 122.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 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, 150.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, 150.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]
    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, 150.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()
