"""Inks the press carries on plates of their own, at every tint.

The Python twin of the `write_spot_color` example in Rust. A spot colour is not
mixed out of the process inks: it is an ink of its own, and a colour in its space
is one number — how much of it goes down. What that number looks like where the
ink is not to hand, on a screen or on a press that does not carry it, is what the
tint transform says.

The second page sets a run list in those same two inks and in nothing else: the
heading on a full-strength plate, every other line on a tint of it, the total on
the second ink, the rules in both, and a closing paragraph whose runs each name
an ink. Everything that paints takes a colour the document carries exactly where
it takes a device one — a cell's background, a cell's text, a row, a table's
rules, a run of styled text, a stamp.

Usage: python examples/write_spot_color.py [out.pdf] [font.ttf]
"""

from __future__ import annotations

import _licence
import _out

import hqf_pdf

# The left edge of everything, and the width of the sheet the page shows.
LEFT = 70.0
WIDTH = 445.0

# The left edge of each tint swatch, and the size of one.
TINT_X = [70.0, 115.0, 160.0, 205.0, 250.0, 295.0, 340.0, 385.0, 430.0, 475.0]
TINT_SIZE = (40.0, 56.0)

# The top of the run list on the second page.
LIST_TOP = 700.0

# One line of the run list: what is being printed, how many sheets, which plates it
# takes and what it comes to.
ITEMS = [
    ["Letterhead, A4", "5 000", "First", "412.00"],
    ["Letterhead, A5", "2 000", "First", "196.00"],
    ["Business cards, both sides", "2 000", "Both", "268.00"],
    ["Compliments slip", "3 000", "Second", "184.00"],
    ["Presentation folder", "1 000", "Both", "590.00"],
    ["Report cover, laminated", "750", "Both", "445.00"],
    ["Window envelope, DL", "5 000", "First", "388.00"],
    ["Wallet envelope, C4", "1 500", "First", "242.00"],
    ["Exhibition panel", "12", "Both", "336.00"],
]

# What the nine lines come to.
TOTAL = "3 061.00"

# The prose under the run list, coloured by the flow that draws it.
PROSE = (
    "An ink of its own is what a house colour is bought as: the press carries it "
    "on a plate of its own, so it goes down at the same strength on every sheet "
    "of every run, which four process inks laid over each other cannot promise. "
    "It costs a plate, so it is spent on the marks a reader recognises the house "
    "by — the name, the rule under it, the panel behind a heading — and the rest "
    "of the work is left to the process inks. This paragraph is one flow of "
    "text, drawn in the first ink at ninety percent, and the words of it were "
    "measured and broken to the width of the list above."
)

# The ten tints each ink is shown at, and what each of them is called.
TINTS = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
TINT_NAMES = ["10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"]


def tint_ramp(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    ink: hqf_pdf.ColorSpaceHandle,
    y: float,
    caption: str,
) -> None:
    """Draws the ten tints of one ink, each labelled with how much goes down."""
    width, height = TINT_SIZE

    for x, tint, name in zip(TINT_X, TINTS, TINT_NAMES):
        content.save_state()
        content.set_fill_space(ink)
        content.set_fill_components([tint])
        content.rect(x, y, width, height)
        content.fill()
        content.restore_state()

        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        content.draw_text(font, 7.0, x, y - 11.0, name)
        content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.2))
    content.draw_text(font, 10.0, LEFT, y + height + 8.0, caption)
    content.restore_state()


def registration(content: hqf_pdf.Content, x: float, y: float) -> None:
    """Draws a printer's crosshair centred on `(x, y)`, in the space in force."""
    arm = 7.0
    content.move_to(x - arm, y)
    content.line_to(x + arm, y)
    content.move_to(x, y - arm)
    content.line_to(x, y + arm)
    content.stroke()

    content.rect(x - 4.0, y - 4.0, 8.0, 8.0)
    content.stroke()


def run_list(
    font: hqf_pdf.FontHandle,
    blue: hqf_pdf.ColorSpaceHandle,
    gold: hqf_pdf.ColorSpaceHandle,
) -> hqf_pdf.Table:
    """The run list, set in the two inks and in nothing else.

    The heading stands on a full-strength plate of the first ink, every other line
    on an eight percent tint of it, the total on the second, and every rule in one
    or the other.
    """
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(54.0),
            hqf_pdf.ColumnWidth.points(74.0),
            hqf_pdf.ColumnWidth.points(66.0),
        ],
        WIDTH,
    )
    table = hqf_pdf.Table(columns)
    table.fill(hqf_pdf.Area.even_rows(), hqf_pdf.Paint.named(blue, [0.08]))
    table.fill(hqf_pdf.Area.header(), hqf_pdf.Paint.named(blue, [1.0]))
    table.rule(
        hqf_pdf.Rule.frame(),
        hqf_pdf.Stroke(0.8, hqf_pdf.Paint.named(blue, [0.55])),
    )
    table.rule(
        hqf_pdf.Rule.horizontal_other(),
        hqf_pdf.Stroke(0.3, hqf_pdf.Paint.named(blue, [0.3])),
    )
    table.rule(
        hqf_pdf.Rule.horizontal(1),
        hqf_pdf.Stroke(1.2, hqf_pdf.Paint.named(gold, [1.0])),
    )
    table.header(1)

    def heading(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            9.0,
            label,
            align=align,
            valign=hqf_pdf.VAlign.Middle,
            color=hqf_pdf.Rgb.gray(1.0),
            padding=hqf_pdf.Padding.symmetric(6.0, 5.0),
        )

    table.push(
        hqf_pdf.Row(
            [
                heading("Item", hqf_pdf.Align.Left),
                heading("Sheets", hqf_pdf.Align.Right),
                heading("Plates", hqf_pdf.Align.Left),
                heading("Price", hqf_pdf.Align.Right),
            ]
        )
    )

    for item in ITEMS:

        def line(column: int, align: hqf_pdf.Align, row=item) -> hqf_pdf.Cell:
            return hqf_pdf.Cell(
                font,
                9.0,
                row[column],
                align=align,
                color=hqf_pdf.Paint.named(blue, [0.95]),
                padding=hqf_pdf.Padding.symmetric(6.0, 5.0),
            )

        table.push(
            hqf_pdf.Row(
                [
                    line(0, hqf_pdf.Align.Left),
                    line(1, hqf_pdf.Align.Right),
                    line(2, hqf_pdf.Align.Left),
                    line(3, hqf_pdf.Align.Right),
                ]
            )
        )

    def total(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            9.5,
            label,
            align=align,
            color=hqf_pdf.Paint.named(blue, [1.0]),
            padding=hqf_pdf.Padding.symmetric(6.0, 6.0),
        )

    table.push(
        hqf_pdf.Row(
            [
                total("Total, nine items, two plates", hqf_pdf.Align.Left),
                total("", hqf_pdf.Align.Right),
                total("", hqf_pdf.Align.Left),
                total(TOTAL, hqf_pdf.Align.Right),
            ],
            fill=hqf_pdf.Paint.named(gold, [0.28]),
        )
    )
    return table


def run_sheet(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    blue: hqf_pdf.ColorSpaceHandle,
    gold: hqf_pdf.ColorSpaceHandle,
) -> None:
    """Draws the run list, the note whose two runs each stand in the ink they
    name, and a specimen mark laid across the whole of it."""
    content.save_state()
    content.set_fill_space(blue)
    content.set_fill_components([1.0])
    content.draw_text(
        font, 15.0, LEFT, 780.0, "The same two inks, through the layout"
    )
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        LEFT,
        762.0,
        "A colour the document carries reaches a cell, a row, a rule and a run "
        "of styled text the",
    )
    content.draw_text(
        font,
        10.0,
        LEFT,
        748.0,
        "way a colour the device answers for does. Not a drop of process ink "
        "goes down below.",
    )
    content.restore_state()

    table = run_list(font, blue, gold)
    placed = table.fit(LEFT, LIST_TOP, LIST_TOP - 260.0, 0)
    height = placed.height
    placed.draw(content)

    first_ink = hqf_pdf.Style(font, 9.5, color=hqf_pdf.Paint.named(blue, [0.9]))
    second_ink = hqf_pdf.Style(font, 9.5, color=hqf_pdf.Paint.named(gold, [1.0]))
    note = hqf_pdf.RichText()
    note.push("The heading stands on a full plate of the first ink, ", first_ink)
    note.push("the total on the second", second_ink)
    note.push(
        ", and the shaded lines on an eight percent tint of the first. One run "
        "of this sentence is set in each of the two.",
        first_ink,
    )
    lines = note.break_lines(WIDTH)
    note_top = LIST_TOP - height - 26.0
    note.draw(content, lines, LEFT, note_top, WIDTH)

    flow = hqf_pdf.TextFlow(
        font, 10.5, color=hqf_pdf.Paint.named(blue, [0.9]), leading=15.0
    )
    prose = flow.break_lines(PROSE, WIDTH)
    flow.draw(
        content,
        prose,
        LEFT,
        note_top - hqf_pdf.RichText.height(lines) - 26.0,
        WIDTH,
    )

    stamp = hqf_pdf.Stamp(
        font, "SPECIMEN", color=hqf_pdf.Paint.named(gold, [0.22])
    )
    stamp.draw(content, LEFT, LIST_TOP - height, WIDTH, height)

    content.save_state()
    content.set_stroke_space(gold)
    content.set_stroke_components([1.0])
    content.set_line_width(0.8)
    content.move_to(LEFT, 92.0)
    content.line_to(LEFT + WIDTH, 92.0)
    content.stroke()
    content.set_fill_space(blue)
    content.set_fill_components([0.55])
    content.draw_text(
        font,
        8.5,
        LEFT,
        78.0,
        "Quoted in two inks: Corporate Blue and Corporate Gold, each on a "
        "plate of its own.",
    )
    content.restore_state()


def main() -> None:
    out = _out.output_path("spot")

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

    blue = document.add_color_space(
        hqf_pdf.Separation.ink(
            "Corporate Blue", hqf_pdf.Cmyk(0.92, 0.58, 0.0, 0.06)
        )
    )
    gold = document.add_color_space(
        hqf_pdf.Separation.ink(
            "Corporate Gold", hqf_pdf.Cmyk(0.0, 0.28, 0.95, 0.04)
        )
    )

    # The colorant every plate answers to: a mark set in it goes down on all of them,
    # which is how a printer sees whether they line up. It is shown as black where no
    # press is involved, so the tint transform runs from the paper to the ink.
    registration_ink = document.add_color_space(
        hqf_pdf.Separation(
            "All",
            hqf_pdf.DeviceSpace.Gray,
            hqf_pdf.Function.exponential(
                (0.0, 1.0), 1.0, endpoints=([1.0], [0.0]), range=[(0.0, 1.0)]
            ),
        )
    )

    content = hqf_pdf.Content()
    content.draw_text(
        font, 15.0, LEFT, 780.0, "Inks the press carries, on plates of their own"
    )
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        LEFT,
        762.0,
        "A spot colour is one number, not four: how much of that ink goes down. "
        "Where the ink is not",
    )
    content.draw_text(
        font,
        10.0,
        LEFT,
        748.0,
        "to hand, the tint transform the file carries shows it — which is what "
        "these swatches are.",
    )
    content.restore_state()

    tint_ramp(content, font, blue, 640.0, "Corporate Blue, one plate, ten tints")
    tint_ramp(content, font, gold, 530.0, "Corporate Gold, a second plate")

    # A piece of work set in the two inks, with the marks a printer lines the plates up
    # by around it.
    bottom, height = 250.0, 190.0
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.75))
    content.set_line_width(0.5)
    content.rect(LEFT, bottom, WIDTH, height)
    content.stroke()
    content.restore_state()

    content.save_state()
    content.set_fill_space(blue)
    content.set_fill_components([1.0])
    content.draw_text(font, 26.0, LEFT + 24.0, bottom + 130.0, "Two inks, one sheet")
    content.set_fill_components([0.15])
    content.rect(LEFT + 24.0, bottom + 40.0, WIDTH - 48.0, 66.0)
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill_space(gold)
    content.set_fill_components([1.0])
    content.rect(LEFT + 24.0, bottom + 118.0, 180.0, 3.0)
    content.fill()
    content.draw_text(
        font,
        11.0,
        LEFT + 40.0,
        bottom + 68.0,
        "Set in the second ink, over a fifteen percent tint of the first.",
    )
    content.restore_state()

    content.save_state()
    content.set_stroke_space(registration_ink)
    content.set_stroke_components([1.0])
    content.set_line_width(0.5)
    for x, y in [
        (LEFT - 16.0, bottom - 16.0),
        (LEFT + WIDTH + 16.0, bottom - 16.0),
        (LEFT - 16.0, bottom + height + 16.0),
        (LEFT + WIDTH + 16.0, bottom + height + 16.0),
    ]:
        registration(content, x, y)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        9.0,
        LEFT,
        bottom - 40.0,
        "The four crosshairs are set in the colorant every plate answers to, "
        "which is what lines them up.",
    )
    content.restore_state()

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

    second = hqf_pdf.Content()
    run_sheet(second, font, blue, gold)
    page = hqf_pdf.Page.a4()
    page.set_content(second)
    document.add_page(page)

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, 2 pages, two inks at {len(TINTS)} "
        f"tints each, {len(ITEMS)} priced lines"
    )


if __name__ == "__main__":
    main()
