"""Shows what an extended graphics state says to the press and to nothing else:
overprinting, halftone screens, transfer curves, the rendering intent and black point
compensation, and how finely a curve is cut into lines.

The Python twin of the `write_press_settings` example in Rust. None of these settings
changes what a screen shows. Each swatch on the page is painted under one of them and
labelled beside it, so the page reads the same on a screen and tells a press, a
proofing tool or a preflight check what to do with each part. The last swatch is
painted under the state that puts every setting back as a page begins.

The file is written as PDF 2.0: the halftone origin and black point compensation are
entries of that version.

Every sentence is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set
is drawn. The halftone swatches are labelled with the name the file writes for their dot
shape, and the colour swatches with the name it writes for their intent or
compensation: those are the same in every language.

Usage: python examples/write_press_settings.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_press_settings.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 everything lines up on.
X = 60.0

# How wide a heading or a paragraph may run.
WIDTH = 475.0

# The size of the running text.
TEXT_SIZE = 8.0

# The size of a swatch's label.
LABEL_SIZE = 6.5

# How far one swatch stands from the next, left edge to left edge.
STEP = 80.0

# The dot shapes a screen can grow, each under the name the file writes.
SPOTS = (
    ("SimpleDot", hqf_pdf.SpotFunction.SimpleDot),
    ("InvertedSimpleDot", hqf_pdf.SpotFunction.InvertedSimpleDot),
    ("DoubleDot", hqf_pdf.SpotFunction.DoubleDot),
    ("InvertedDoubleDot", hqf_pdf.SpotFunction.InvertedDoubleDot),
    ("CosineDot", hqf_pdf.SpotFunction.CosineDot),
    ("Double", hqf_pdf.SpotFunction.Double),
    ("InvertedDouble", hqf_pdf.SpotFunction.InvertedDouble),
    ("Line", hqf_pdf.SpotFunction.Line),
    ("LineX", hqf_pdf.SpotFunction.LineX),
    ("LineY", hqf_pdf.SpotFunction.LineY),
    ("Round", hqf_pdf.SpotFunction.Round),
    ("Ellipse", hqf_pdf.SpotFunction.Ellipse),
    ("EllipseA", hqf_pdf.SpotFunction.EllipseA),
    ("InvertedEllipseA", hqf_pdf.SpotFunction.InvertedEllipseA),
    ("EllipseB", hqf_pdf.SpotFunction.EllipseB),
    ("EllipseC", hqf_pdf.SpotFunction.EllipseC),
    ("InvertedEllipseC", hqf_pdf.SpotFunction.InvertedEllipseC),
    ("Square", hqf_pdf.SpotFunction.Square),
    ("Cross", hqf_pdf.SpotFunction.Cross),
    ("Rhomboid", hqf_pdf.SpotFunction.Rhomboid),
    ("Diamond", hqf_pdf.SpotFunction.Diamond),
)

# The four rendering intents, each under the name the file writes.
INTENTS = (
    ("Perceptual", hqf_pdf.RenderingIntent.perceptual()),
    ("RelativeColorimetric", hqf_pdf.RenderingIntent.relative_colorimetric()),
    ("Saturation", hqf_pdf.RenderingIntent.saturation()),
    ("AbsoluteColorimetric", hqf_pdf.RenderingIntent.absolute_colorimetric()),
)

# The three settings of black point compensation, each under the name the file writes.
COMPENSATIONS = (
    ("ON", hqf_pdf.BlackPointCompensation.On),
    ("OFF", hqf_pdf.BlackPointCompensation.Off),
    ("Default", hqf_pdf.BlackPointCompensation.Reader),
)


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

    What is not language stays out of it: the halftone and colour swatches are labelled
    with the names the file writes.
    """

    # The line at the head of the page.
    title: str
    # The paragraph under it.
    intro: str
    # The heading above the overprint swatches.
    overprint: str
    # The label under each overprint swatch, in the order they are painted.
    overprint_labels: tuple[str, str, str]
    # The heading above the halftone swatches.
    screens: str
    # The label of the swatch screened ink by ink.
    per_ink: str
    # The label of the swatch whose screen is precise and moved.
    accurate: str
    # The heading above the transfer swatches.
    transfer: str
    # The label under each transfer swatch, in the order they are painted.
    transfer_labels: tuple[str, str, str]
    # The heading above the colour swatches.
    color: str
    # The heading above the path swatches.
    paths: str
    # The label under each path swatch, in the order they are painted.
    path_labels: tuple[str, str, str, str]


# The page in English.
ENGLISH = Words(
    title="What a graphics state tells the press",
    intro=(
        "None of these settings changes what a screen shows. Each swatch is painted "
        "under one of them and labelled with what it asks: a press, a proofing tool or "
        "a preflight check reads the rest."
    ),
    overprint=(
        "Overprinting: a yellow square over a cyan bar, the cyan left in place under "
        "it."
    ),
    overprint_labels=(
        "fill overprints, zero keeps",
        "all overprints, zero erases",
        "only the stroke overprints",
    ),
    screens="Halftone screens: the shape each dot grows into as the grey darkens.",
    per_ink="one screen per ink",
    accurate="precise, moved",
    transfer="Transfer curves: the tone laid down bent away from the tone asked for.",
    transfer_labels=(
        "one curve, every ink",
        "one curve per ink",
        "the page’s own curve",
    ),
    color=(
        "Rendering intents and black point compensation, read where a colour is "
        "converted."
    ),
    paths=(
        "How finely curves and shadings are approximated, and how a thin stroke is "
        "snapped."
    ),
    path_labels=(
        "coarse flatness",
        "smooth shadings",
        "stroke adjustment",
        "everything reset",
    ),
)

# The page in French.
FRENCH = Words(
    title="Ce qu’un état graphique dit à l’imprimeur",
    intro=(
        "Aucun de ces réglages ne change l’affichage à l’écran. Chaque pavé est peint "
        "sous l’un d’eux, avec à côté ce qu’il demande : le reste est lu par la presse, "
        "l’outil d’épreuvage ou le contrôle prépresse."
    ),
    overprint=(
        "Surimpression : un carré jaune sur une barre cyan, qui reste en place dessous."
    ),
    overprint_labels=(
        "fond en surimpression, zéro gardé",
        "tout en surimpression, zéro effacé",
        "contour seul en surimpression",
    ),
    screens="Trames : la forme que prend chaque point quand le gris fonce.",
    per_ink="une trame par encre",
    accurate="précise, décalée",
    transfer="Courbes de transfert : le ton déposé s’écarte du ton demandé.",
    transfer_labels=(
        "une courbe commune",
        "une courbe par encre",
        "la courbe de la page",
    ),
    color=(
        "Intentions de rendu et compensation du point noir, lues à la conversion des "
        "couleurs."
    ),
    paths=(
        "La finesse d’approximation des courbes et des dégradés, et le calage d’un "
        "trait fin."
    ),
    path_labels=(
        "découpage grossier",
        "dégradés lissés",
        "trait calé",
        "tout remis à zéro",
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Wat een grafische status de pers vertelt",
    intro=(
        "Geen van deze instellingen verandert wat een scherm toont. Elk staal wordt "
        "onder een ervan geschilderd en heeft als label wat het vraagt: een pers, een "
        "proefhulpmiddel of een preflightcontrole leest de rest."
    ),
    overprint=(
        "Overdrukken: een geel vierkant over een cyaan balk; het cyaan eronder blijft "
        "staan."
    ),
    overprint_labels=(
        "vulling drukt over, nul behoudt",
        "alles drukt over, nul wist",
        "alleen de lijn drukt over",
    ),
    screens="Rasters: de vorm waartoe elk punt groeit naarmate het grijs donkerder wordt.",
    per_ink="één raster per inkt",
    accurate="precies, verschoven",
    transfer="Overdrachtscurven: de neergelegde toon wijkt af van de gevraagde toon.",
    transfer_labels=(
        "één curve voor alles",
        "één curve per inkt",
        "paginacurve",
    ),
    color=(
        "Weergave-intenties en zwartpuntcompensatie, gelezen waar een kleur wordt "
        "omgezet."
    ),
    paths=(
        "Hoe fijn curven en arceringen benaderd worden, en hoe een dunne lijn wordt "
        "uitgelijnd."
    ),
    path_labels=(
        "grove vlakheid",
        "gladde arceringen",
        "lijnaanpassing",
        "alles teruggezet",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="O que um estado gráfico diz à gráfica",
    intro=(
        "Nenhuma destas definições muda o que um ecrã mostra. Cada amostra é pintada "
        "sob uma delas e leva escrito o que pede: uma máquina de impressão, uma "
        "ferramenta de provas ou uma verificação prévia leem o resto."
    ),
    overprint=(
        "Sobreimpressão: um quadrado amarelo sobre uma barra ciano, que fica por "
        "baixo."
    ),
    overprint_labels=(
        "preenchimento sobreimprime, zero mantém",
        "tudo sobreimprime, zero apaga",
        "só o traço sobreimprime",
    ),
    screens="Retículas: a forma em que cresce cada ponto à medida que o cinzento escurece.",
    per_ink="uma retícula por tinta",
    accurate="precisa, deslocada",
    transfer="Curvas de transferência: o tom impresso afasta-se do tom pedido.",
    transfer_labels=(
        "a mesma curva",
        "uma curva por tinta",
        "a curva da página",
    ),
    color=(
        "Intenções de reprodução e compensação do ponto preto, lidas onde uma cor é "
        "convertida."
    ),
    paths=(
        "Com que finura se aproximam curvas e sombreados, e como se ajusta um traço "
        "fino."
    ),
    path_labels=(
        "planura grosseira",
        "sombreados suaves",
        "ajuste de traço",
        "tudo reposto",
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Ciò che uno stato grafico dice alla macchina da stampa",
    intro=(
        "Nessuna di queste impostazioni cambia ciò che mostra uno schermo. Ogni "
        "campione è dipinto sotto una di esse e porta scritto ciò che chiede: una "
        "macchina da stampa, uno strumento di prova o un controllo preliminare "
        "leggono il resto."
    ),
    overprint=(
        "Sovrastampa: un quadrato giallo su una barra ciano, che resta sotto."
    ),
    overprint_labels=(
        "il riempimento sovrastampa, zero conserva",
        "tutto sovrastampa, zero cancella",
        "solo il tratto sovrastampa",
    ),
    screens="Retini: la forma in cui cresce ogni punto man mano che il grigio scurisce.",
    per_ink="un retino per colore",
    accurate="preciso, spostato",
    transfer="Curve di trasferimento: il tono steso si discosta dal tono chiesto.",
    transfer_labels=(
        "la stessa curva",
        "una per inchiostro",
        "la curva della pagina",
    ),
    color=(
        "Intenti di rendering e compensazione del punto nero, letti dove si converte "
        "un colore."
    ),
    paths=(
        "Con quale finezza si approssimano curve e sfumature, e come si aggancia un "
        "tratto sottile."
    ),
    path_labels=(
        "planarità grossolana",
        "sfumature morbide",
        "regolazione del tratto",
        "tutto azzerato",
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Lo que un estado gráfico dice a la imprenta",
    intro=(
        "Ninguno de estos ajustes cambia lo que muestra una pantalla. Cada muestra se "
        "pinta bajo uno de ellos y lleva escrito lo que pide: una prensa, una "
        "herramienta de pruebas o un control previo leen el resto."
    ),
    overprint=(
        "Sobreimpresión: un cuadrado amarillo sobre una barra cian, que se conserva "
        "debajo."
    ),
    overprint_labels=(
        "el relleno sobreimprime, cero conserva",
        "todo sobreimprime, cero borra",
        "solo el trazo sobreimprime",
    ),
    screens="Tramas de semitono: la forma en que crece cada punto al oscurecerse el gris.",
    per_ink="una trama por tinta",
    accurate="precisa, desplazada",
    transfer="Curvas de transferencia: el tono impreso se aparta del tono pedido.",
    transfer_labels=(
        "la misma curva",
        "una curva por tinta",
        "la curva de la página",
    ),
    color=(
        "Intenciones de reproducción y compensación del punto negro, leídas donde se "
        "convierte un color."
    ),
    paths=(
        "Con qué finura se aproximan curvas y sombreados, y cómo se ajusta un trazo "
        "fino."
    ),
    path_labels=(
        "planitud gruesa",
        "sombreados suaves",
        "ajuste del trazo",
        "todo restablecido",
    ),
)

# The page in German.
GERMAN = Words(
    title="Was ein Grafikzustand der Druckmaschine sagt",
    intro=(
        "Keine dieser Einstellungen ändert, was ein Bildschirm zeigt. Jedes Farbfeld "
        "wird unter einer davon gemalt und mit dem beschriftet, was sie verlangt: Den "
        "Rest liest eine Druckmaschine, ein Proofwerkzeug oder eine Preflight-Prüfung."
    ),
    overprint=(
        "Überdrucken: ein gelbes Quadrat über einem Cyanbalken, das Cyan bleibt "
        "darunter stehen."
    ),
    overprint_labels=(
        "Fläche überdruckt, null bleibt",
        "alles überdruckt, null löscht",
        "nur der Strich überdruckt",
    ),
    screens="Rasterungen: die Form, zu der jeder Punkt wächst, wenn das Grau dunkler wird.",
    per_ink="ein Raster je Farbe",
    accurate="präzise, verschoben",
    transfer="Übertragungskurven: der aufgetragene Ton, weg vom verlangten gebogen.",
    transfer_labels=(
        "eine Kurve, alle Farben",
        "eine Kurve je Farbe",
        "Kurve der Seite",
    ),
    color=(
        "Wiedergabeabsichten und Tiefenkompensierung, gelesen, wo eine Farbe "
        "umgerechnet wird."
    ),
    paths=(
        "Wie fein Kurven und Schattierungen angenähert werden und wie ein dünner "
        "Strich eingerastet wird."
    ),
    path_labels=(
        "grobe Glättung",
        "weiche Schattierungen",
        "Strichanpassung",
        "alles zurückgesetzt",
    ),
)



# 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 paragraph(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    left: float,
    top: float,
    width: float,
    text: str,
) -> None:
    """Sets text from (left, top), broken into lines width wide, at size."""
    flow = hqf_pdf.TextFlow(font, size)
    lines = flow.break_lines(text, width)
    flow.draw(content, lines, left, top, width)


def swatch(
    document: hqf_pdf.Document,
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    at: tuple[float, float],
    state: hqf_pdf.ExtGState,
    color: hqf_pdf.Cmyk,
    label: str,
) -> None:
    """Paints a swatch of color at `at` under state, and labels it underneath."""
    left, bottom = at
    added = document.add_ext_gstate(state)
    content.save_state()
    content.set_ext_gstate(added)
    content.set_fill(color)
    content.rect(left, bottom, 70.0, 26.0)
    content.fill()
    content.restore_state()
    paragraph(content, font, LABEL_SIZE, left, bottom - 8.0, STEP - 4.0, label)


def curve(exponent: float) -> hqf_pdf.Function:
    """A curve that lifts the middle tones: the input raised to the power exponent."""
    return hqf_pdf.Function.exponential((0.0, 1.0), exponent)


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_version(hqf_pdf.Version.V2_0)
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    grey = hqf_pdf.Cmyk(0.0, 0.0, 0.0, 0.5)

    content = hqf_pdf.Content()
    paragraph(content, font, 14.0, X, 790.0, WIDTH, words.title)
    paragraph(content, font, TEXT_SIZE, X, 768.0, WIDTH, words.intro)

    # Overprinting: the cyan bar is painted plainly, and the yellow square over it under
    # each state in turn.
    paragraph(content, font, TEXT_SIZE, X, 730.0, WIDTH, words.overprint)
    overprints = (
        hqf_pdf.ExtGState(
            fill_overprint=True, overprint_mode=hqf_pdf.OverprintMode.KeepZero
        ),
        hqf_pdf.ExtGState(
            stroke_overprint=True,
            fill_overprint=True,
            overprint_mode=hqf_pdf.OverprintMode.EraseZero,
        ),
        hqf_pdf.ExtGState(stroke_overprint=True, fill_overprint=False),
    )
    left = X
    for state, label in zip(overprints, words.overprint_labels):
        content.set_fill(hqf_pdf.Cmyk(1.0, 0.0, 0.0, 0.0))
        content.rect(left, 686.0, 140.0, 20.0)
        content.fill()
        added = document.add_ext_gstate(state)
        content.save_state()
        content.set_ext_gstate(added)
        content.set_fill(hqf_pdf.Cmyk(0.0, 0.0, 1.0, 0.0))
        content.set_stroke(hqf_pdf.Cmyk(0.0, 0.0, 1.0, 0.0))
        content.set_line_width(3.0)
        content.rect(left + 30.0, 676.0, 40.0, 40.0)
        content.fill_and_stroke()
        content.restore_state()
        paragraph(content, font, LABEL_SIZE, left, 666.0, 150.0, label)
        left += 160.0

    # Halftone screens: one swatch per dot shape, six to a row, then the two that screen
    # ink by ink and precisely.
    paragraph(content, font, TEXT_SIZE, X, 640.0, WIDTH, words.screens)
    spots = [
        (
            hqf_pdf.ExtGState(
                halftone=hqf_pdf.Halftone.every(hqf_pdf.Screen(60.0, 45.0, spot))
            ),
            name,
        )
        for name, spot in SPOTS
    ]
    spots.append(
        (
            hqf_pdf.ExtGState(
                halftone=hqf_pdf.Halftone.per_ink(
                    [
                        (
                            "Cyan",
                            hqf_pdf.Screen(60.0, 15.0, hqf_pdf.SpotFunction.Round),
                        ),
                        (
                            "Magenta",
                            hqf_pdf.Screen(60.0, 75.0, hqf_pdf.SpotFunction.Round),
                        ),
                        (
                            "Yellow",
                            hqf_pdf.Screen(60.0, 0.0, hqf_pdf.SpotFunction.Round),
                        ),
                    ],
                    hqf_pdf.Screen(60.0, 45.0, hqf_pdf.SpotFunction.Ellipse),
                )
            ),
            words.per_ink,
        )
    )
    spots.append(
        (
            hqf_pdf.ExtGState(
                halftone=hqf_pdf.Halftone.every(
                    hqf_pdf.Screen(150.0, 45.0, hqf_pdf.SpotFunction.EllipseC).accurate(
                        True
                    )
                ),
                halftone_origin=(X, 400.0),
            ),
            words.accurate,
        )
    )
    bottom = 598.0
    for first in range(0, len(spots), 6):
        left = X
        for state, label in spots[first : first + 6]:
            swatch(document, content, font, (left, bottom), state, grey, label)
            left += STEP
        bottom -= 46.0

    # Transfer curves.
    paragraph(content, font, TEXT_SIZE, X, 420.0, WIDTH, words.transfer)
    transfers = (
        hqf_pdf.Transfer.every(curve(0.6)),
        hqf_pdf.Transfer.per_ink(curve(0.8), curve(0.9), curve(1.0), curve(1.2)),
        hqf_pdf.Transfer.page(),
    )
    left = X
    for transfer, label in zip(transfers, words.transfer_labels):
        swatch(
            document,
            content,
            font,
            (left, 378.0),
            hqf_pdf.ExtGState(transfer=transfer),
            hqf_pdf.Cmyk(0.2, 0.5, 0.0, 0.1),
            label,
        )
        left += STEP

    # Rendering intents and black point compensation.
    paragraph(content, font, TEXT_SIZE, X, 340.0, WIDTH, words.color)
    left = X
    for label, intent in INTENTS:
        swatch(
            document,
            content,
            font,
            (left, 298.0),
            hqf_pdf.ExtGState(rendering_intent=intent),
            hqf_pdf.Cmyk(0.0, 0.8, 0.9, 0.0),
            label,
        )
        left += STEP
    left = X
    for label, compensation in COMPENSATIONS:
        swatch(
            document,
            content,
            font,
            (left, 252.0),
            hqf_pdf.ExtGState(black_point_compensation=compensation),
            hqf_pdf.Cmyk(0.6, 0.0, 0.3, 0.7),
            label,
        )
        left += STEP

    # How curves and shadings are approximated, and how a thin stroke is snapped: four
    # rings, the last under the state that puts everything back.
    paragraph(content, font, TEXT_SIZE, X, 214.0, WIDTH, words.paths)
    rings = (
        hqf_pdf.ExtGState(flatness=20.0),
        hqf_pdf.ExtGState(smoothness=0.01),
        hqf_pdf.ExtGState(stroke_adjustment=True),
        hqf_pdf.ExtGState.initial(),
    )
    left = X
    for state, label in zip(rings, words.path_labels):
        added = document.add_ext_gstate(state)
        content.save_state()
        content.set_ext_gstate(added)
        content.set_stroke(hqf_pdf.Cmyk(0.0, 0.0, 0.0, 1.0))
        content.set_line_width(0.3)
        content.circle(left + 35.0, 172.0, 22.0)
        content.stroke()
        content.restore_state()
        paragraph(content, font, LABEL_SIZE, left, 140.0, STEP - 4.0, label)
        left += STEP

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