"""Several named colorants at once, each on a plate of its own.

The Python twin of the `write_devicen` example in Rust. A colour in such a space
is one tint per colorant, and one program says what the lot of them look like
where those plates are not to hand. Naming some of the process plates and no
others lays ink on those and leaves the rest as they stand; naming inks of its
own is how a press that carries more than four is painted in.

The words the page draws are held in `Words`, one set per language, and `HQF_PDF_LANG`
picks which set is drawn. The colorants are not words: their names are written into the
file and drawn back from it.

Usage: python examples/write_devicen.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_devicen.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 of everything.
LEFT = 70.0


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

    What is not language stays out of it: a colorant's name is written into the file and
    drawn back from it, and so are the programs and the tints.
    """

    # The title across the top of the page.
    title: str
    # The two lines under the title, each already broken to the page.
    lead: tuple[str, str]
    # The heading of the panel of subsets.
    subsets: str
    # The heading of the panel of two inks, and the line under it.
    inks: str
    inks_under: str


# The page in English.
ENGLISH = Words(
    title="Several plates at once, each with a tint of its own",
    lead=(
        "Naming some of the process plates and no others lays ink on those and "
        "leaves the rest as",
        "they stand, which painting in full CMYK cannot do. One program fills in "
        "the plates left out.",
    ),
    subsets="Subsets of the process plates, and the program each one is shown through",
    inks="Two inks of the press's own on one space, every tint of each against the other",
    inks_under="Down the side, Corporate Blue. Across the top, Corporate Gold. "
    "Two numbers say a colour here.",
)

# The page in French.
FRENCH = Words(
    title="Plusieurs plaques à la fois, chacune à son intensité",
    lead=(
        "Nommer certaines plaques et pas les autres pose de l'encre sur celles-là "
        "et laisse les",
        "autres intactes, ce que la quadrichromie ne peut pas. Un programme remplit "
        "les manquantes.",
    ),
    subsets="Sous-ensembles des plaques d'impression, et le programme qui montre chacun",
    inks="Deux encres propres à la presse sur un espace, chaque intensité de l'une "
    "contre l'autre",
    inks_under="Sur le côté, Corporate Blue. En haut, Corporate Gold. "
    "Deux nombres disent une couleur ici.",
)

# 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 subsets():
    """Every subset of the process plates the first panel shows: the plates it
    names, the program that fills in the ones it leaves out, and the tint each
    named plate is shown at."""
    return [
        (
            ["Cyan"],
            [hqf_pdf.Op.integer(0)] * 3,
            [0.8],
        ),
        (
            ["Magenta"],
            [hqf_pdf.Op.integer(0)] * 3
            + [hqf_pdf.Op.integer(4), hqf_pdf.Op.integer(1), hqf_pdf.Op.roll()],
            [0.8],
        ),
        (
            ["Yellow"],
            [hqf_pdf.Op.integer(0)] * 3
            + [hqf_pdf.Op.integer(4), hqf_pdf.Op.integer(2), hqf_pdf.Op.roll()],
            [0.8],
        ),
        (
            ["Black"],
            [hqf_pdf.Op.integer(0)] * 3
            + [hqf_pdf.Op.integer(4), hqf_pdf.Op.integer(3), hqf_pdf.Op.roll()],
            [0.8],
        ),
        (
            ["Cyan", "Magenta"],
            [hqf_pdf.Op.integer(0)] * 2,
            [0.7, 0.7],
        ),
        (
            ["Cyan", "Yellow"],
            [hqf_pdf.Op.integer(0), hqf_pdf.Op.exchange(), hqf_pdf.Op.integer(0)],
            [0.7, 0.7],
        ),
        (
            ["Magenta", "Yellow"],
            [hqf_pdf.Op.integer(0)] * 2
            + [hqf_pdf.Op.integer(4), hqf_pdf.Op.integer(1), hqf_pdf.Op.roll()],
            [0.7, 0.7],
        ),
        (
            ["Cyan", "Magenta", "Yellow"],
            [hqf_pdf.Op.integer(0)],
            [0.6, 0.6, 0.6],
        ),
    ]


# The left edge of each column of the first panel, and the size of one swatch.
SUBSET_X = [70.0, 185.0, 300.0, 415.0]
SUBSET_SIZE = (100.0, 52.0)
# The baseline the first row of swatches sits on, and the drop to the second.
SUBSET_Y = 620.0
SUBSET_DROP = 108.0

# The two inks the second panel paints in, as the process inks show them at full
# strength.
BLUE = [0.92, 0.58, 0.0, 0.06]
GOLD = [0.0, 0.28, 0.95, 0.04]

# The tints the duotone grid runs through, along both of its axes.
DUOTONE_TINTS = [0.0, 0.25, 0.5, 0.75, 1.0]
# The left edge and the top of the duotone grid, and the size of one cell.
DUOTONE_ORIGIN = (110.0, 355.0)
DUOTONE_CELL = 52.0


def mix_two_inks():
    """The program mixing two inks: each output is the first ink's share of that
    process plate taken at the first tint, plus the second ink's taken at the
    second.

    Both tints stay at the bottom of the stack while the four outputs are worked
    out above them, so each one is reached again by counting down past the
    outputs already there; the pair is then turned to the top and thrown away.
    """
    body = []
    for plate, (first, second) in enumerate(zip(BLUE, GOLD)):
        reach = plate + 1
        body += [
            hqf_pdf.Op.integer(reach),
            hqf_pdf.Op.index(),
            hqf_pdf.Op.real(first),
            hqf_pdf.Op.multiply(),
            hqf_pdf.Op.integer(reach),
            hqf_pdf.Op.index(),
            hqf_pdf.Op.real(second),
            hqf_pdf.Op.multiply(),
            hqf_pdf.Op.add(),
        ]
    body += [
        hqf_pdf.Op.integer(6),
        hqf_pdf.Op.integer(4),
        hqf_pdf.Op.roll(),
        hqf_pdf.Op.pop(),
        hqf_pdf.Op.pop(),
    ]
    return hqf_pdf.Calculation([(0.0, 1.0)] * 2, [(0.0, 1.0)] * 4, body)


def subset_transform(colorants, body):
    """The function a subset of the process plates is shown through."""
    return hqf_pdf.Calculation(
        [(0.0, 1.0)] * len(colorants), [(0.0, 1.0)] * 4, body
    )


def subset_swatch(content, font, space, colorants, transform, tints, x, y):
    """Draw one swatch, with the plates it names above it and the program that
    fills in the rest below."""
    width, height = SUBSET_SIZE

    content.save_state()
    content.set_fill_space(space)
    content.set_fill_components(tints)
    content.rect(x, y, width, height)
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.2))
    content.draw_text(font, 8.0, x, y + height + 7.0, " ".join(colorants))
    content.set_fill(hqf_pdf.Rgb.gray(0.45))
    content.draw_text(font, 7.0, x, y - 11.0, transform.program())
    content.restore_state()


def duotone_grid(content, font, space):
    """Draw the grid of the two inks against one another, every tint of the first
    crossed with every tint of the second."""
    left, top = DUOTONE_ORIGIN

    for row, blue in enumerate(DUOTONE_TINTS):
        down = top - row * DUOTONE_CELL
        for column, gold in enumerate(DUOTONE_TINTS):
            across = left + column * DUOTONE_CELL
            content.save_state()
            content.set_fill_space(space)
            content.set_fill_components([blue, gold])
            content.rect(across, down, DUOTONE_CELL - 4.0, DUOTONE_CELL - 4.0)
            content.fill()
            content.restore_state()

        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.45))
        content.draw_text(
            font, 7.0, LEFT, down + DUOTONE_CELL / 2.0 - 7.0, f"{blue * 100:.0f}%"
        )
        content.restore_state()

    for column, gold in enumerate(DUOTONE_TINTS):
        across = left + column * DUOTONE_CELL
        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.45))
        content.draw_text(
            font, 7.0, across, top + DUOTONE_CELL - 1.0, f"{gold * 100:.0f}%"
        )
        content.restore_state()


def heading(content, font, words):
    """Draw the title and the two lines saying what the page is showing."""
    content.draw_text(font, 15.0, LEFT, 780.0, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(font, 10.0, LEFT, 762.0, words.lead[0])
    content.draw_text(font, 10.0, LEFT, 748.0, words.lead[1])
    content.restore_state()


def panel_heading(content, font, y, title, under):
    """Draw one panel's heading, with the line under it that a panel may have."""
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.2))
    content.draw_text(font, 11.0, LEFT, y, title)
    if under is not None:
        content.set_fill(hqf_pdf.Rgb.gray(0.45))
        content.draw_text(font, 8.0, LEFT, y - 16.0, under)
    content.restore_state()


def subset_panel(document, content, font):
    """Draw every subset of the process plates, four to a row."""
    for place, (colorants, body, tints) in enumerate(subsets()):
        transform = subset_transform(colorants, body)
        space = document.add_color_space(
            hqf_pdf.DeviceN(colorants, hqf_pdf.DeviceSpace.Cmyk, transform)
        )
        x = SUBSET_X[place % len(SUBSET_X)]
        y = SUBSET_Y - (place // len(SUBSET_X)) * SUBSET_DROP
        subset_swatch(content, font, space, colorants, transform, tints, x, y)


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

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

    content = hqf_pdf.Content()
    heading(content, font, words)
    panel_heading(content, font, 700.0, words.subsets, None)
    subset_panel(document, content, font)

    panel_heading(content, font, 440.0, words.inks, words.inks_under)
    inks = document.add_color_space(
        hqf_pdf.DeviceN(
            ["Corporate Blue", "Corporate Gold"],
            hqf_pdf.DeviceSpace.Cmyk,
            mix_two_inks(),
        )
    )
    duotone_grid(content, font, inks)

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

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {len(subsets())} subsets of the "
        "process plates and two inks of its own"
    )


if __name__ == "__main__":
    main()
