"""Lays every image the tests ship with on one page, each captioned with what the
file itself declares.

The Python twin of the `write_image_gallery` example in Rust.

Nothing in the captions is written by hand: each line is read back out of the image
after it was parsed, so the page is a statement of what the library understood rather
than of what the example was told. A file that declares nothing says so, which is the
point of showing it next to the ones that do.

What each caption says is written in the language `HQF_PDF_LANG` names. The names of
the files are not, and neither is `sRGB`: both are what is written on the disk and in
the file.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# Every image committed for the tests.
IMAGES = Path(__file__).resolve().parents[2] / "hqf-pdf" / "tests" / "images"

# The page, and the grid laid over it.
MARGIN = 30.0
COLUMNS = 4
ROWS = 6

# The tallest and widest a thumbnail is drawn.
THUMBNAIL = (110.0, 92.0)

# The caption under each thumbnail.
CAPTION_SIZE = 5.6
CAPTION_LEADING = 7.4

# Ink.
TEXT = hqf_pdf.Rgb(0.15, 0.16, 0.2)
FADED = hqf_pdf.Rgb(0.42, 0.44, 0.5)
TILE = hqf_pdf.Rgb(0.95, 0.96, 0.97)

# The name of the colour profile a file may declare it was read through. It is what the
# profile is called, not a word of any language.
SRGB = "sRGB"


@dataclass(frozen=True)
class Plural:
    """A word in its two numbers.

    English and French both keep the singular for one and take the plural from two
    upwards, which is the whole of the rule the captions need: a count of bits is never
    nought, and a table of colours never holds fewer than two.
    """

    # The form the word takes for one.
    one: str
    # The form it takes for every other count.
    many: str

    def of(self, count: int) -> str:
        """The form this word takes for ``count``."""
        return self.one if count == 1 else self.many


@dataclass(frozen=True)
class Words:
    """The words the captions are written in, one set per language.

    The names of the files are not among them, and neither is the name of the colour
    profile a file may declare it was read through.
    """

    # What the page is called, drawn at its head.
    title: str
    # What the document is called in what the file says of itself, which is a name
    # rather than the sentence drawn on the page.
    file_title: str
    # What stands between the two sides of a picture, in pixels and in dots.
    by: str
    # What a measurement in pixels is called.
    pixels: str
    # What a depth of one and of more than one is called.
    bits: Plural
    # What a resolution is called.
    dots: str
    # What one pixel of a grey picture stands for.
    grey: str
    # What one pixel of a three-channel picture stands for.
    rgb: str
    # What one pixel of a four-ink picture stands for.
    cmyk: str
    # What stands before the size of a palette.
    table_of: str
    # What a palette holds, of one colour and of more.
    colours: Plural
    # What a picture in a space of none of those kinds stands for.
    other_space: str
    # What stands before the way up a file declares.
    seen: str
    # The ways up, in the order of the numbers a file names them by: mirrored left to
    # right, upside down, mirrored top to bottom, mirrored and turned left, turned
    # right, mirrored and turned right, turned left, and last the one a number nothing
    # names falls back to.
    ways_up: tuple[str, ...]
    # What a picture that carries an opacity for every pixel declares.
    alpha: str
    # What a picture that drops one colour declares.
    color_key: str
    # What stands before the name of the profile a picture was read through.
    read_through: str
    # What a file that declares nothing beyond its shape says instead.
    nothing_else: str


# The captions in English.
ENGLISH = Words(
    title="Every picture the tests ship with, and what each file says about itself",
    file_title="hqf-pdf image gallery",
    by="by",
    pixels="pixels",
    bits=Plural(one="bit", many="bits"),
    dots="dots to the inch",
    grey="grey",
    rgb="red, green, blue",
    cmyk="four inks",
    table_of="a table of",
    colours=Plural(one="colour", many="colours"),
    other_space="colours of some other kind",
    seen="seen",
    ways_up=(
        "mirrored left to right",
        "upside down",
        "mirrored top to bottom",
        "mirrored, turned left",
        "turned right",
        "mirrored, turned right",
        "turned left",
        "the way it is stored",
    ),
    alpha="opacity per pixel",
    color_key="one colour left out",
    read_through="read through",
    nothing_else="declaring nothing else of itself",
)

# The captions in French.
FRENCH = Words(
    title="Toutes les images livrées avec les tests, et ce que chaque fichier dit "
    "de lui-même",
    file_title="galerie d'images hqf-pdf",
    by="sur",
    pixels="pixels",
    bits=Plural(one="bit", many="bits"),
    dots="points par pouce",
    grey="du gris",
    rgb="du rouge, du vert, du bleu",
    cmyk="quatre encres",
    table_of="une table de",
    colours=Plural(one="couleur", many="couleurs"),
    other_space="des couleurs d'un autre genre",
    seen="vue",
    ways_up=(
        "en miroir gauche-droite",
        "à l'envers",
        "en miroir haut-bas",
        "en miroir, tournée à gauche",
        "tournée à droite",
        "en miroir, tournée à droite",
        "tournée à gauche",
        "telle qu'elle est stockée",
    ),
    alpha="opacité par pixel",
    color_key="une couleur laissée de côté",
    read_through="lue à travers",
    nothing_else="ne déclarant rien d'autre",
)

# 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 colour_of(image: hqf_pdf.Image, words: Words) -> str:
    """What one pixel of the image stands for, in the fewest words that still say it."""
    palette = image.color_space.palette
    if palette is not None:
        colours = len(palette) // 3
        return f"{words.table_of} {colours} {words.colours.of(colours)}"
    return {1: words.grey, 3: words.rgb, 4: words.cmyk}.get(
        image.color_space.components, words.other_space
    )


def facts(image: hqf_pdf.Image, words: Words) -> list[str]:
    """What the file says about itself, one statement at a time.

    A file that says nothing beyond its shape says so: the point of the page is that
    both kinds sit side by side.
    """
    bits = image.bits_per_component
    facts = [
        f"{image.width} {words.by} {image.height} {words.pixels}",
        colour_of(image, words),
        f"{bits} {words.bits.of(bits)}",
    ]

    stated = []
    resolution = image.resolution
    if resolution is not None:
        stated.append(
            f"{resolution.x:.0f} {words.by} {resolution.y:.0f} {words.dots}"
        )
    orientation = image.orientation
    if orientation is not None:
        stated.append(f"{words.seen} {way_up(words, orientation.tag)}")
    if image.has_alpha:
        stated.append(words.alpha)
    if image.color_key is not None:
        stated.append(words.color_key)
    if image.icc_profile is not None:
        stated.append(f"{words.read_through} {SRGB}")

    facts.extend(stated if stated else [words.nothing_else])
    return facts


def packed(font: hqf_pdf.FontHandle, width: float, statements: list[str]) -> list[str]:
    """The statements laid end to end, broken into lines that fit ``width``.

    Nothing is dropped: a caption that will not fit on one line takes as many as it
    needs, which is what keeps the page a full account of what was read.
    """
    lines: list[str] = []
    for statement in statements:
        joined = f"{lines[-1]}, {statement}" if lines else ""
        if lines and font.measure(joined, CAPTION_SIZE) <= width:
            lines[-1] = joined
        else:
            lines.append(statement)
    return lines


def way_up(words: Words, tag: int) -> str:
    """The way up an ``Exif`` header names by its number, in words. A number nothing
    names falls to the last of them."""
    if 2 <= tag <= 8:
        return words.ways_up[tag - 2]
    return words.ways_up[7]


def text(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    at: tuple[float, float],
    colour: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text, left-aligned, in a colour of its own."""
    content.set_fill(colour)
    content.draw_text(font, size, at[0], at[1], s)


def text_fitted(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    at: tuple[float, float],
    width: float,
    colour: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text, shortened until it fits the width it is given."""
    line = s
    while font.measure(line, size) > width and len(line) > 1:
        line = line[:-2] + "…"
    text(content, font, size, at, colour, line)


def tile(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    handle: hqf_pdf.ImageHandle,
    lines: list[str],
    at: tuple[float, float],
    cell: tuple[float, float],
) -> None:
    """Draws one tile: the picture inside its box, and what the file says under it."""
    x, y = at
    cell_width, cell_height = cell
    caption_height = CAPTION_LEADING * len(lines)
    box_height = cell_height - caption_height - 6.0

    content.set_fill(TILE)
    content.rect(x, y + caption_height + 6.0, cell_width, box_height)
    content.fill()

    # The picture keeps its proportions inside the box, and sits in the middle of it.
    width, height = handle.fit_within(
        min(THUMBNAIL[0], cell_width - 8.0), min(THUMBNAIL[1], box_height)
    )
    content.draw_image(
        handle,
        x + (cell_width - width) / 2.0,
        y + caption_height + 6.0 + (box_height - height) / 2.0,
        width,
        height,
    )

    for index, line in enumerate(lines):
        colour = TEXT if index == 0 else FADED
        text_fitted(
            content,
            font,
            CAPTION_SIZE,
            (x, y + caption_height - CAPTION_LEADING * (index + 1) + 2.0),
            cell_width,
            colour,
            line,
        )


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", words.file_title)
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    page = hqf_pdf.Page.a4()
    cell_width = (page.width - 2.0 * MARGIN) / COLUMNS - 6.0

    tiles = []
    for path in sorted(path for path in IMAGES.iterdir() if path.is_file()):
        image = hqf_pdf.Image.from_path(path)
        lines = [path.name, *packed(font, cell_width, facts(image, words))]
        tiles.append((document.add_image(image), lines))

    content = hqf_pdf.Content()

    text(
        content,
        font,
        13.0,
        (MARGIN, page.height - MARGIN - 10.0),
        TEXT,
        words.title,
    )

    top = page.height - MARGIN - 34.0
    cell_height = (top - MARGIN) / ROWS

    for index, (handle, lines) in enumerate(tiles):
        column, row = index % COLUMNS, index // COLUMNS
        if row >= ROWS:
            print(
                f"{len(tiles)} pictures do not fit on one page; the rest are left off"
            )
            break

        tile(
            content,
            font,
            handle,
            lines,
            (MARGIN + (cell_width + 6.0) * column, top - cell_height * (row + 1)),
            (cell_width, cell_height - 6.0),
        )

    page.set_content(content)
    document.add_page(page)

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


if __name__ == "__main__":
    main()
