"""Fits one picture into boxes of one size eight ways, and labels each.

The Python twin of the `write_fitted` example in Rust. A `FitBox` says how a picture
is sized to a box, where it sits in it, how far the box is inset first, and how far
the picture is turned and mirrored on its way in. Every panel hands the same picture
and the same box to a different policy, and draws what comes back the same way:
concatenate the matrix the policy gives, then draw the picture at the origin at its
natural size. No panel computes the scale or the offset of its picture itself.

The panel that covers its box is the one case that overflows on purpose, so it is
clipped to the box it covers; every other panel stays inside.

A second page lays out eight more: the picture at its natural size, then twice as large
and clipped; shrunk to fit when it is twice as large, and left as it is when it is half
as large; a quarter as large at each of the nine named anchors; half as large at a point
a quarter in from the left and a quarter down, upright and unmirrored; turned upside
down; and mirrored top to bottom. Those panels hand the policy the picture's size
multiplied by the panel's scale, and draw the picture at that size.

The title and the eight captions are held in `Words`, once per language, and
`HQF_PDF_LANG` picks which set is drawn. The first four captions open with the name
the library gives the policy they describe — ``contain``, ``cover``, ``stretch`` —
which is the same in every language.

Usage: python examples/write_fitted.py [out.pdf]
       HQF_PDF_LANG=fr python examples/write_fitted.py
"""

from __future__ import annotations

import math
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The picture every panel fits: the JPEG committed for the tests.
IMAGES = Path(__file__).resolve().parents[2] / "hqf-pdf" / "tests" / "images"
PHOTO = IMAGES / "photo.jpg"

PAGE_WIDTH = 595.276
MARGIN = 56.0
# The gap between the two columns of panels.
GAP = 24.0
# The box every panel fits its picture into.
BOX_WIDTH = (PAGE_WIDTH - 2.0 * MARGIN - GAP) / 2.0
BOX_HEIGHT = 130.0
# The top of the first row of boxes, and the drop from one row to the next.
FIRST_ROW = 750.0
ROW_PITCH = 176.0
# How far under a box its caption's baseline sits.
CAPTION_DROP = 14.0


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

    The first four captions open with the name the library gives the policy they
    describe — ``contain``, ``cover``, ``stretch`` — and those names are the same
    in every language.
    """

    # The line at the head of the page.
    title: str
    # What is written under each box, in the order the panels are laid out.
    captions: tuple[str, str, str, str, str, str, str, str]
    # The line at the head of the second page.
    more_title: str
    # What is written under each box of the second page, in the order `more_panels` lays
    # them out.
    more_captions: tuple[str, str, str, str, str, str, str, str]


# The page in English.
ENGLISH = Words(
    title="One picture, one box, eight fitting policies",
    captions=(
        "contain: as large as fits, its shape kept",
        "cover: no gap left, the overflow clipped",
        "stretch: the box filled, its shape lost",
        "contain, top left, inset 12 points",
        "a quarter turn anticlockwise",
        "a quarter turn clockwise",
        "turned 20 degrees, still inside its box",
        "mirrored left to right",
    ),
    more_title="The same picture, sized and placed other ways",
    more_captions=(
        "natural: its own size, whatever the box",
        "natural, twice as large, what hangs over clipped",
        "shrink to fit, twice as large: made smaller",
        "shrink to fit, half as large: left, mirrored both ways",
        "natural, a quarter as large, at the nine anchors",
        "a quarter in from the left and a quarter down",
        "a half turn",
        "mirrored top to bottom",
    ),
)

# The page in French.
FRENCH = Words(
    title="Une image, une boîte, huit façons de l’ajuster",
    captions=(
        "contain : aussi grande que possible, proportions gardées",
        "cover : aucun vide laissé, le débordement rogné",
        "stretch : la boîte remplie, les proportions perdues",
        "contain, en haut à gauche, 12 points de retrait",
        "un quart de tour, sens antihoraire",
        "un quart de tour, sens horaire",
        "tournée de 20 degrés, toujours dans sa boîte",
        "inversée de gauche à droite",
    ),
    more_title="La même image, dimensionnée et placée autrement",
    more_captions=(
        "natural : à sa propre taille, quelle que soit la boîte",
        "natural, deux fois plus grande, le débordement rogné",
        "shrink to fit, deux fois plus grande : réduite",
        "shrink to fit, demi-taille : à gauche, double miroir",
        "natural, quatre fois moins grande, aux neuf ancres",
        "à un quart du bord gauche et à un quart du haut",
        "un demi-tour",
        "en miroir de haut en bas",
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Eén afbeelding, één kader, acht manieren van passen",
    captions=(
        "contain: zo groot als past, vorm behouden",
        "cover: geen gat, het overschot afgesneden",
        "stretch: het kader gevuld, de vorm kwijt",
        "contain, linksboven, 12 punten ingesprongen",
        "een kwartslag tegen de klok in",
        "een kwartslag met de klok mee",
        "20 graden gedraaid, nog binnen het kader",
        "links-rechts gespiegeld",
    ),
    more_title="Dezelfde afbeelding, op andere manieren bemeten en geplaatst",
    more_captions=(
        "natural: eigen grootte, wat het kader ook is",
        "natural, twee keer zo groot, het uitstekende afgesneden",
        "verkleinen om te passen, twee keer zo groot: kleiner gemaakt",
        "verkleinen om te passen, half zo groot: links, in beide richtingen gespiegeld",
        "natural, een kwart zo groot, op de negen ankers",
        "een kwart vanaf links en een kwart naar beneden",
        "een halve slag",
        "boven-onder gespiegeld",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Uma imagem, uma caixa, oito formas de a encaixar",
    captions=(
        "contain: o maior que cabe, com a sua forma",
        "cover: sem vazios, o excesso recortado",
        "stretch: a caixa cheia, a forma perdida",
        "contain, em cima à esquerda, margem de 12 pontos",
        "um quarto de volta para a esquerda",
        "um quarto de volta para a direita",
        "rodada 20 graus, ainda dentro da caixa",
        "espelhada da esquerda para a direita",
    ),
    more_title="A mesma imagem, dimensionada e colocada de outras formas",
    more_captions=(
        "natural: o seu tamanho, seja qual for a caixa",
        "natural, o dobro, o que sobra recortado",
        "reduzir para caber, o dobro: fica mais pequena",
        "reduzir para caber, metade: à esquerda, espelhada nos dois sentidos",
        "natural, um quarto do tamanho, nas nove âncoras",
        "a um quarto da esquerda e um quarto para baixo",
        "meia volta",
        "espelhada de cima para baixo",
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Un’immagine, un riquadro, otto modi di adattarla",
    captions=(
        "contain: la più grande che ci sta, forma conservata",
        "cover: nessun vuoto, l’eccesso ritagliato",
        "stretch: il riquadro pieno, la forma persa",
        "contain, in alto a sinistra, margine di 12 punti",
        "un quarto di giro in senso antiorario",
        "un quarto di giro in senso orario",
        "ruotata di 20 gradi, ancora nel suo riquadro",
        "specchiata da sinistra a destra",
    ),
    more_title="La stessa immagine, dimensionata e collocata in altri modi",
    more_captions=(
        "natural: la sua dimensione, qualunque sia il riquadro",
        "natural, il doppio, la parte sporgente ritagliata",
        "riduci per adattare, il doppio: rimpicciolita",
        "riduci per adattare, la metà: a sinistra, specchiata nei due sensi",
        "natural, un quarto della dimensione, sui nove ancoraggi",
        "a un quarto da sinistra e un quarto in basso",
        "mezzo giro",
        "specchiata dall’alto in basso",
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Una imagen, una caja, ocho formas de encajarla",
    captions=(
        "contain: lo más grande que cabe, con su forma",
        "cover: sin huecos, lo que sobra recortado",
        "stretch: la caja llena, la forma perdida",
        "contain, arriba a la izquierda, margen de 12 puntos",
        "un cuarto de vuelta a la izquierda",
        "un cuarto de vuelta a la derecha",
        "girada 20 grados, aún dentro de su caja",
        "reflejada de izquierda a derecha",
    ),
    more_title="La misma imagen, dimensionada y colocada de otras formas",
    more_captions=(
        "natural: su propio tamaño, sea cual sea la caja",
        "natural, el doble, lo que sobresale recortado",
        "reducir para caber, el doble: se hace más pequeña",
        "reducir para caber, la mitad: a la izquierda, reflejada en ambos sentidos",
        "natural, un cuarto del tamaño, en los nueve anclajes",
        "a un cuarto desde la izquierda y un cuarto hacia abajo",
        "media vuelta",
        "reflejada de arriba abajo",
    ),
)

# The page in German.
GERMAN = Words(
    title="Ein Bild, ein Rahmen, acht Arten der Einpassung",
    captions=(
        "contain: so groß, wie es passt, die Form bleibt",
        "cover: keine Lücke, der Überstand abgeschnitten",
        "stretch: Rahmen gefüllt, die Form verloren",
        "contain, oben links, 12 Punkt eingerückt",
        "eine Vierteldrehung gegen den Uhrzeigersinn",
        "eine Vierteldrehung im Uhrzeigersinn",
        "um 20 Grad gedreht, noch im Rahmen",
        "von links nach rechts gespiegelt",
    ),
    more_title="Dasselbe Bild, anders bemessen und platziert",
    more_captions=(
        "natural: eigene Größe, unabhängig vom Rahmen",
        "natural, doppelt so groß, Überstand abgeschnitten",
        "shrink to fit, doppelt so groß: verkleinert",
        "shrink to fit, halb so groß: links, doppelt gespiegelt",
        "natural, ein Viertel so groß, an den neun Ankern",
        "ein Viertel von links und ein Viertel von oben",
        "eine halbe Drehung",
        "von oben nach unten gespiegelt",
    ),
)


# 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}


@dataclass(frozen=True)
class Panel:
    """What a panel says it does, the policies it draws the picture by, once each,
    whether what it draws has to be held to the box, and what the picture's size is
    multiplied by before it is fitted."""

    caption: str
    fitted: list[hqf_pdf.FitBox]
    clipped: bool = False
    scale: float = 1.0


def panels(words: Words) -> list[Panel]:
    """The eight policies, in the order they are laid out: the three sizing modes and
    one of them anchored and inset first, then the three turns and the mirror, each
    under the caption `words` gives it."""
    fitted = [
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Contain), False),
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Cover), True),
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Stretch), False),
        (
            hqf_pdf.FitBox(
                hqf_pdf.FitMode.Contain,
                anchor=hqf_pdf.Anchor.top_left(),
                margin=12.0,
            ),
            False,
        ),
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, turn=hqf_pdf.Turn.left()), False),
        (hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, turn=hqf_pdf.Turn.right()), False),
        (
            hqf_pdf.FitBox(
                hqf_pdf.FitMode.Contain,
                turn=hqf_pdf.Turn.angle(math.radians(20.0)),
            ),
            False,
        ),
        (
            hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, mirror=hqf_pdf.Mirror.LeftToRight),
            False,
        ),
    ]
    return [
        Panel(caption, [box], clipped=clipped)
        for (box, clipped), caption in zip(fitted, words.captions)
    ]


# The nine named anchors, bottom row first, each left to right.
ANCHORS = (
    hqf_pdf.Anchor.bottom_left(),
    hqf_pdf.Anchor.bottom(),
    hqf_pdf.Anchor.bottom_right(),
    hqf_pdf.Anchor.left(),
    hqf_pdf.Anchor.center(),
    hqf_pdf.Anchor.right(),
    hqf_pdf.Anchor.top_left(),
    hqf_pdf.Anchor.top(),
    hqf_pdf.Anchor.top_right(),
)


def more_panels(words: Words) -> list[Panel]:
    """The second page's eight policies, in the order they are laid out: the natural
    size, then twice as large and clipped; shrinking to fit twice and half as large;
    the nine anchors; a point between them, upright and not mirrored; the half turn and
    the mirror top to bottom."""
    natural = hqf_pdf.FitMode.Natural
    fitted = [
        ([hqf_pdf.FitBox(natural)], False, 1.0),
        ([hqf_pdf.FitBox(natural)], True, 2.0),
        ([hqf_pdf.FitBox(hqf_pdf.FitMode.ShrinkToFit)], False, 2.0),
        (
            [hqf_pdf.FitBox(hqf_pdf.FitMode.ShrinkToFit, mirror=hqf_pdf.Mirror.Both)],
            False,
            0.5,
        ),
        ([hqf_pdf.FitBox(natural, anchor=anchor) for anchor in ANCHORS], False, 0.25),
        (
            [
                hqf_pdf.FitBox(
                    natural,
                    anchor=hqf_pdf.Anchor.fraction(0.25, 0.75),
                    turn=hqf_pdf.Turn.upright(),
                    mirror=hqf_pdf.Mirror.Neither,
                )
            ],
            False,
            0.5,
        ),
        (
            [hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, turn=hqf_pdf.Turn.upside_down())],
            False,
            1.0,
        ),
        (
            [hqf_pdf.FitBox(hqf_pdf.FitMode.Contain, mirror=hqf_pdf.Mirror.TopToBottom)],
            False,
            1.0,
        ),
    ]
    return [
        Panel(caption, boxes, clipped=clipped, scale=scale)
        for (boxes, clipped, scale), caption in zip(fitted, words.more_captions)
    ]


def panel_box(index: int) -> tuple[float, float, float, float]:
    """The box the panel at `index` fits into: two to a row, filled left to right."""
    column = index % 2
    row = index // 2
    x = MARGIN + column * (BOX_WIDTH + GAP)
    top = FIRST_ROW - row * ROW_PITCH
    return (x, top - BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT)


def draw_panel(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    image: hqf_pdf.ImageHandle,
    panel: Panel,
    box: tuple[float, float, float, float],
) -> None:
    """Draws one panel: its box's outline, the picture fitted into it, and its
    caption underneath."""
    x, y, width, height = box

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.75))
    content.set_line_width(0.5)
    content.rect(x, y, width, height)
    content.stroke()
    content.restore_state()

    natural = image.size
    size = (natural[0] * panel.scale, natural[1] * panel.scale)
    content.save_state()
    if panel.clipped:
        content.rect(x, y, width, height)
        content.clip()
        content.end_path()
    for fitted in panel.fitted:
        content.save_state()
        content.transform(fitted.matrix(size, box))
        content.draw_image(image, 0.0, 0.0, size[0], size[1])
        content.restore_state()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(font, 8.5, x, y - CAPTION_DROP, panel.caption)
    content.restore_state()


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.DEFAULT_FONT))
    image = document.add_image(hqf_pdf.Image.from_path(PHOTO))

    drawn = panels(words)
    more = more_panels(words)
    for title, laid in ((words.title, drawn), (words.more_title, more)):
        content = hqf_pdf.Content()
        content.draw_text(font, 16.0, MARGIN, 790.0, title)
        for index, panel in enumerate(laid):
            draw_panel(content, font, image, panel, panel_box(index))

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

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {len(drawn) + len(more)} panels of one "
        f"{image.width}x{image.height} picture"
    )


if __name__ == "__main__":
    main()
