"""Shows three things an extended graphics state opens: half-opacity fills that
overlap and mix, one colour laid over another in four blend modes, and overlapping
letters of one text object knocked out or composited.

The Python twin of the `write_transparency` example in Rust. The opacity panel
draws three rectangles, each at half opacity, so the colours show through one
another where they overlap. The blend panel lays the same orange square over a
blue bar four times, once in each of four modes, so the mode each square is
painted in can be read from the colour it leaves. The knockout panel sets the same
line twice at half opacity, each letter crossed by a stroke that overlaps it: under
`TK true` the text object is painted as one and the overlaps come out as light as the
rest, under `TK false` each glyph is composited on its own and the overlaps come out
darker. A reader that ignores the flag shows the two lines alike.

The three headings are held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn. Each square is labelled with the name the file writes for its blend
mode, and each line with the entry its state writes, which are the same in every
language.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The left edge the panels line up on.
X = 80.0

# The line the knockout panel sets twice: each letter followed by a combining stroke
# that takes no room of its own, so the stroke lies across the letter.
CROSSED = "O\u0338O\u0338O\u0338O\u0338"


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

    What is not language stays out of it: each square is labelled with the name the file
    writes for its blend mode, and each crossed line with the entry its state writes.
    """

    # The heading above the opacity panel.
    opacity: str
    # The heading above the blend panel.
    blends: str
    # The heading above the knockout panel.
    knockout: str


# The page in English.
ENGLISH = Words(
    opacity="Half-opacity fills overlap and mix.",
    blends="One orange square over a blue bar, in four blend modes.",
    knockout=(
        "Overlapping letters at half opacity: knocked out on the left, composited "
        "with one another on the right."
    ),
)

# The page in French.
FRENCH = Words(
    opacity="Des aplats à moitié transparents se chevauchent et se mélangent.",
    blends="Un carré orange sur une barre bleue, dans quatre modes de fusion.",
    knockout=(
        "Des lettres qui se chevauchent, à moitié transparentes : en défonce à "
        "gauche, composées entre elles à droite."
    ),
)


# 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 heading(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    top: float,
    label: str,
    left: float,
) -> None:
    """Sets a one-line label with its baseline at top, left edge at left."""
    flow = hqf_pdf.TextFlow(handle, 8.0)
    lines = flow.break_lines(label, 400.0)
    flow.draw(content, lines, left, top, 400.0)


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

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

    # The states the three panels apply, added once and shared.
    half = document.add_ext_gstate(hqf_pdf.ExtGState(fill_alpha=0.5))
    modes = (
        ("Normal", hqf_pdf.BlendMode.Normal),
        ("Multiply", hqf_pdf.BlendMode.Multiply),
        ("Screen", hqf_pdf.BlendMode.Screen),
        ("Difference", hqf_pdf.BlendMode.Difference),
    )
    blends = [
        (label, document.add_ext_gstate(hqf_pdf.ExtGState(blend_mode=mode)))
        for label, mode in modes
    ]
    knockouts = (
        (
            "TK true",
            document.add_ext_gstate(
                hqf_pdf.ExtGState(fill_alpha=0.5, text_knockout=True)
            ),
        ),
        (
            "TK false",
            document.add_ext_gstate(
                hqf_pdf.ExtGState(fill_alpha=0.5, text_knockout=False)
            ),
        ),
    )

    content = hqf_pdf.Content()

    # The opacity panel: three overlapping rectangles, each at half opacity.
    heading(content, handle, 720.0, words.opacity, X)
    colors = (
        (0.0, hqf_pdf.Rgb(0.85, 0.15, 0.15)),
        (30.0, hqf_pdf.Rgb(0.15, 0.65, 0.20)),
        (60.0, hqf_pdf.Rgb(0.15, 0.30, 0.85)),
    )
    for offset, color in colors:
        content.save_state()
        content.set_ext_gstate(half)
        content.set_fill(color)
        content.rect(X + offset, 590.0, 90.0, 90.0)
        content.fill()
        content.restore_state()

    # The blend panel: an orange square over a blue bar, once per mode.
    heading(content, handle, 520.0, words.blends, X)
    square = 80.0
    gap = 20.0
    left = X
    for label, state in blends:
        content.set_fill(hqf_pdf.Rgb(0.15, 0.35, 0.80))
        content.rect(left, 380.0, square, square)
        content.fill()
        content.save_state()
        content.set_ext_gstate(state)
        content.set_fill(hqf_pdf.Rgb(0.95, 0.55, 0.10))
        content.rect(left + 20.0, 360.0, square, square)
        content.fill()
        content.restore_state()
        heading(content, handle, 350.0, label, left)
        left += square + gap

    # The knockout panel: the crossed line twice, the state applied before the text
    # object opens, since a text object reads the flag as it begins.
    heading(content, handle, 300.0, words.knockout, X)
    crossed = hqf_pdf.TextFlow(handle, 48.0, color=hqf_pdf.Rgb(0.15, 0.30, 0.85))
    lines = crossed.break_lines(CROSSED, 200.0)
    left = X
    for label, state in knockouts:
        content.save_state()
        content.set_ext_gstate(state)
        crossed.draw(content, lines, left, 280.0, 200.0)
        content.restore_state()
        heading(content, handle, 210.0, label, left)
        left += 200.0

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

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


if __name__ == "__main__":
    main()
