"""Draws one plan on six layers a reader can show and hide.

The Python twin of the `write_layers` example in Rust. The walls are the page's own ink
and are always there. Everything else belongs to a layer: the furniture and the
dimensions start shown, the notes start hidden, and the draft mark is looked at but
never printed. The file also says what three of the layers are: the draft mark is a
watermark, a grid laid over the plan says it is an aid for whoever drew it and asks to
start hidden, and the crop marks at the corners of the sheet are printer's marks. The
furniture layer names the program it came from, Plan Studio, and says it holds a
technical design. The chairs are one drawing placed six times, and the drawing itself belongs to the furniture
layer, so hiding that layer hides every chair. Open the file and reading software's
layers panel lists all six; print it and the draft mark is gone without anyone touching
that panel.

The page is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. A layer's name is language too: reading software's panel shows it, and the legend
under the plan names the same field, so the panel and the page can never disagree.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Callable

import _language
import _licence
import _out

import hqf_pdf

# The plan's outer wall: where it sits on the page and how big it is.
PLAN = (80.0, 380.0, 435.0, 320.0)

# The two distances the plan is measured at. Neither is language.
ALONG = "7.25 m"
ACROSS = "5.00 m"

# Where each chair stands, by its lower left corner: three along each long side of the
# table.
CHAIRS = (
    (140.0, 662.0),
    (173.0, 662.0),
    (206.0, 662.0),
    (140.0, 578.0),
    (173.0, 578.0),
    (206.0, 578.0),
)

# The corners of the trimmed sheet the crop marks point at.
TRIM = (36.0, 36.0, 559.0, 806.0)


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

    A layer's name is here: reading software's panel shows it, and so does the legend.
    The two distances are not: a metre is a metre.
    """

    # The line at the head of the page.
    title: str
    # What stands under it, saying what a layer is.
    intro: str
    # What each layer is called, in the order they are added. Reading software's panel
    # lists these, and the legend names them again.
    layers: tuple[str, str, str, str, str, str]
    # What the legend says each layer holds and how it starts.
    holdings: tuple[str, str, str, str, str, str]
    # The notes the hidden layer holds, in the order they are placed.
    notes: tuple[str, str, str]
    # The word the draft mark is stamped in.
    draft: str
    # The two lines under the legend, saying that the draft mark takes itself off the
    # printed page.
    printing: tuple[str, str]


# The page in English.
ENGLISH = Words(
    title="One plan, six layers",
    intro=(
        "The walls are always there. Everything else is a layer the reader can show "
        "and hide."
    ),
    layers=("Furniture", "Dimensions", "Notes", "Draft", "Grid", "Crop marks"),
    holdings=(
        "shown; turn it off and the rooms stand empty, chairs too",
        "shown; the distances around the plan",
        "hidden; turn it on to read them",
        "shown on screen, never printed; the file calls it a watermark",
        "hidden; an aid for whoever drew the plan, not part of it",
        "shown; the file calls them printer's marks",
    ),
    notes=(
        "Table seats six.",
        "Bed against the party wall.",
        "Counter, waste under.",
    ),
    draft="DRAFT",
    printing=(
        "The draft mark carries its own answer for the printer, so nothing has to",
        "be switched off before the page is printed.",
    ),
)

# The page in French.
FRENCH = Words(
    title="Un plan, six calques",
    intro=(
        "Les murs sont toujours là. Tout le reste est un calque à afficher ou "
        "masquer."
    ),
    layers=("Mobilier", "Cotes", "Notes", "Brouillon", "Grille", "Traits de coupe"),
    holdings=(
        "affiché ; désactivez-le et les pièces sont vides, chaises comprises",
        "affiché ; les distances autour du plan",
        "masqué ; activez-le pour les lire",
        "affiché à l'écran, jamais imprimé ; le fichier le dit filigrane",
        "masqué ; une aide pour qui a dessiné le plan, pas le plan",
        "affiché ; le fichier les dit repères d'imprimeur",
    ),
    notes=(
        "Table pour six personnes.",
        "Lit contre le mur mitoyen.",
        "Plan de travail, poubelle dessous.",
    ),
    draft="BROUILLON",
    printing=(
        "La mention de brouillon porte sa propre consigne pour l'imprimante :",
        "rien n'a besoin d'être masqué avant d'imprimer la page.",
    ),
)


# 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 walls(content: hqf_pdf.Content) -> None:
    """Draws the walls: the outer room and the partition that splits it."""
    x, y, width, height = PLAN
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.15))
    content.set_line_width(3.0)
    content.rect(x, y, width, height)
    content.stroke()
    content.move_to(x + 265.0, y)
    content.line_to(x + 265.0, y + 190.0)
    content.stroke()
    content.restore_state()


def furniture(content: hqf_pdf.Content) -> None:
    """Draws the furniture: a table, a bed and a counter, each a filled outline."""
    x, y, _, height = PLAN
    pieces = [
        (x + 40.0, y + height - 110.0, 120.0, 70.0),
        (x + 300.0, y + height - 130.0, 90.0, 110.0),
        (x + 290.0, y + 30.0, 110.0, 40.0),
    ]
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.85, 0.88, 0.93))
    content.set_stroke(hqf_pdf.Rgb(0.35, 0.45, 0.6))
    content.set_line_width(1.0)
    for px, py, pw, ph in pieces:
        content.rect(px, py, pw, ph)
        content.fill()
        content.rect(px, py, pw, ph)
        content.stroke()
    content.restore_state()


def grid(content: hqf_pdf.Content) -> None:
    """Draws the grid: a line every 29 points across the plan and every 32 up it."""
    x, y, width, height = PLAN
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb(0.55, 0.75, 0.9))
    content.set_line_width(0.3)
    across = x
    for __ in range(1, 15):
        across += 29.0
        content.move_to(across, y)
        content.line_to(across, y + height)
    up = y
    for __ in range(1, 10):
        up += 32.0
        content.move_to(x, up)
        content.line_to(x + width, up)
    content.stroke()
    content.restore_state()


def chair() -> hqf_pdf.Drawing:
    """The chair every place at the table shows: a filled outline in the colours of
    the furniture."""
    content = hqf_pdf.Content()
    content.set_fill(hqf_pdf.Rgb(0.85, 0.88, 0.93))
    content.set_stroke(hqf_pdf.Rgb(0.35, 0.45, 0.6))
    content.set_line_width(1.0)
    content.rect(0.5, 0.5, 13.0, 9.0)
    content.fill()
    content.rect(0.5, 0.5, 13.0, 9.0)
    content.stroke()
    return hqf_pdf.Drawing(content, hqf_pdf.Rect(0.0, 0.0, 14.0, 10.0))


def crop_marks(content: hqf_pdf.Content) -> None:
    """Draws the crop marks: two short lines at each corner of the trimmed sheet,
    standing off it."""
    left, bottom, right, top = TRIM
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.0))
    content.set_line_width(0.5)
    for corner_x, corner_y, out_x, out_y in (
        (left, bottom, -1.0, -1.0),
        (right, bottom, 1.0, -1.0),
        (left, top, -1.0, 1.0),
        (right, top, 1.0, 1.0),
    ):
        content.move_to(corner_x + out_x * 6.0, corner_y)
        content.line_to(corner_x + out_x * 24.0, corner_y)
        content.move_to(corner_x, corner_y + out_y * 6.0)
        content.line_to(corner_x, corner_y + out_y * 24.0)
    content.stroke()
    content.restore_state()


def dimensions(content: hqf_pdf.Content, font: hqf_pdf.FontHandle) -> None:
    """Draws a line under the plan and one beside it, each with the distance it
    stands for."""
    x, y, width, height = PLAN
    below = y - 26.0
    beside = x - 46.0

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb(0.2, 0.5, 0.35))
    content.set_fill(hqf_pdf.Rgb(0.2, 0.5, 0.35))
    content.set_line_width(0.8)

    content.move_to(x, below)
    content.line_to(x + width, below)
    content.move_to(x, below - 5.0)
    content.line_to(x, below + 5.0)
    content.move_to(x + width, below - 5.0)
    content.line_to(x + width, below + 5.0)
    content.move_to(beside, y)
    content.line_to(beside, y + height)
    content.move_to(beside - 5.0, y)
    content.line_to(beside + 5.0, y)
    content.move_to(beside - 5.0, y + height)
    content.line_to(beside + 5.0, y + height)
    content.stroke()

    content.draw_text(font, 9.0, x + width / 2.0 - 18.0, below + 8.0, ALONG)
    content.draw_text(font, 9.0, beside + 6.0, y + height / 2.0, ACROSS)
    content.restore_state()


def notes(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws what someone reading the plan wants said, and a reader who is only
    looking at the rooms does not."""
    x, y, _, height = PLAN
    places = [
        (x + 44.0, y + height - 130.0),
        (x + 292.0, y + height - 148.0),
        (x + 292.0, y + 16.0),
    ]
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.7, 0.25, 0.1))
    for (nx, ny), line in zip(places, words.notes):
        content.draw_text(font, 8.0, nx, ny, line)
    content.restore_state()


def legend(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws the legend under the plan: what each layer holds and how it starts."""
    baseline = 300.0
    for name, what in zip(words.layers, words.holdings):
        content.draw_text(font, 10.0, 80.0, baseline, name)
        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        content.draw_text(font, 10.0, 170.0, baseline, what)
        content.restore_state()
        baseline -= 18.0

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        80.0,
        baseline - 12.0,
        words.printing[0],
    )
    content.draw_text(font, 10.0, 80.0, baseline - 26.0, words.printing[1])
    content.restore_state()


def on_layer(
    content: hqf_pdf.Content,
    layer: hqf_pdf.LayerHandle,
    body: Callable[[hqf_pdf.Content], None],
) -> None:
    """Draws `body` inside `layer`, so reading software shows and hides all of it at
    once."""
    content.begin_layer(layer)
    body(content)
    content.end_marked()


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

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

    furniture_layer = document.add_layer(
        hqf_pdf.Layer(words.layers[0]).made_by("Plan Studio", hqf_pdf.LayerWork.Technical)
    )
    dimensions_layer = document.add_layer(hqf_pdf.Layer(words.layers[1]))
    notes_layer = document.add_layer(hqf_pdf.Layer(words.layers[2]).visible(False))
    draft_layer = document.add_layer(
        hqf_pdf.Layer(words.layers[3])
        .on_screen(True)
        .printed(False)
        .purpose(hqf_pdf.LayerPurpose.Watermark)
    )
    grid_layer = document.add_layer(
        hqf_pdf.Layer(words.layers[4]).visible(False).intent(hqf_pdf.LayerIntent.Design)
    )
    marks_layer = document.add_layer(
        hqf_pdf.Layer(words.layers[5]).purpose(hqf_pdf.LayerPurpose.PrintersMarks)
    )
    placed_chair = document.add_drawing(chair().layer(furniture_layer))

    content = hqf_pdf.Content()
    content.draw_text(font, 15.0, 80.0, 750.0, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        80.0,
        730.0,
        words.intro,
    )
    content.restore_state()

    walls(content)
    on_layer(content, grid_layer, grid)
    on_layer(content, furniture_layer, furniture)
    # The chairs are placed outside any layer's run: the drawing names its layer itself.
    for x, y in CHAIRS:
        content.draw_form(placed_chair, x, y, 1.0)
    on_layer(content, dimensions_layer, lambda target: dimensions(target, font))
    on_layer(content, notes_layer, lambda target: notes(target, font, words))

    def draft(target: hqf_pdf.Content) -> None:
        x, y, width, height = PLAN
        stamp = hqf_pdf.Stamp(
            font,
            words.draft,
            slant=hqf_pdf.Slant.Up,
            color=hqf_pdf.Rgb(0.8, 0.3, 0.3),
        )
        stamp.draw(target, x, y, width, height)

    on_layer(content, draft_layer, draft)
    on_layer(content, marks_layer, crop_marks)
    legend(content, font, words)

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

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


if __name__ == "__main__":
    main()
