"""Writes a page of PDF417 codes, drawn as stacked bars.

The Python twin of the `write_pdf417` example in Rust: the same page, through
the binding rather than through the library directly.

Whether a PDF417 code works is not a question the page can answer, and not one
a human eye can: it is answered by a scanner. So the page carries what each
code says under it, and `scripts/check_pdf417.sh` points a decoder at the
rendered image and compares.

The head of the sheet says what the stacked bars are for, so that the page is
worth something to whoever opens it without the code beside it. Those words are held in
`Words`, once per language, and `HQF_PDF_LANG` picks which set the sheet is headed in.
What the codes carry stands apart from them: a scanner reads it, not a person, and it is
the same in every language.

A second page sets the same kind of code at five of the nine levels of correction, one
of them handed over as UTF-8 bytes that name their character set, and four built other
ways, in one column. Each says under its payload the level it was built at and the
correction codewords that level adds.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# What the codes carry: a tracking link, a serial number, and a line of mixed
# punctuation.
CARRIED = [
    "https://example.test/track/FR-1964413",
    "SN:2026-07-19/ACME-4472",
    "a-Z 0..9 +*#% and on",
]

# How many data columns each code is drawn in, which is what settles how wide the symbol
# comes out: the rows follow from the text.
COLUMNS = 4

# The width of one module, in points. Six pixels to a module at 288dpi, so every
# module's edge lands on a pixel boundary.
MODULE = 1.5

# The width of one module on the second page, in points: six pixels to a module at
# 288dpi, as on the first.
SMALL_MODULE = 1.5

# What the codes of the second page carry: levels 0 and 5, four built other ways, and
# level 8.
LEVELLED = (
    "LEVEL 0",
    "Zürich ✓",
    "COLUMNS 3",
    "PLAIN BYTES",
    "LEVEL BYTES",
    "COLUMN BYTES",
    "SHAPE 8",
)

# Where the foot of the first code sits, in points up from the foot of the sheet.
TOP = 660.0

# How far in from the left edge of the sheet the head of the page is set. The quiet zone
# of each code starts here too, so the heading stands over the left edge of the block of
# codes.
MARGIN = 72.0

# Where the baseline of the heading sits, in points up from the foot of the sheet.
HEAD_TOP = 794.0

# The size the heading is set at, in points.
HEADING = 16.0

# The size the lines under the heading are set at, in points.
BODY = 10.5

# How far under the heading the first line beneath it sits, in points.
HEAD_GAP = 24.0

# How far below one line under the heading the next one sits, in points.
LINE_STEP = 15.0

@dataclass(frozen=True)
class Words:
    """Every word the sheet is headed in, in one language."""

    # What the page says it is, at its head and in what the file says of itself.
    title: str
    # What the page says under its heading.
    lines: tuple[str, str]
    # The second page's heading.
    more_title: str
    # The line under a code of the second page that says its level of correction;
    # `{level}` and `{codewords}` stand for what is read back.
    level: str


# The head of the sheet in English.
ENGLISH = Words(
    title="PDF417 codes, drawn as stacked bars",
    lines=(
        "A PDF417 code is rows of bars stacked one over another, and it holds a whole",
        "form rather than a number. Under each one is what a scanner reads back.",
    ),
    more_title="Levels of correction, and codes built other ways",
    level="level {level}: {codewords} correction codewords",
)

# The sheet in French.
FRENCH = Words(
    title="Des codes PDF417, dessinés en barres empilées",
    lines=(
        (
            "Un code PDF417 est fait de rangées de barres empilées, et il contient un "
            "formulaire"
        ),
        "entier plutôt qu’un numéro. Sous chacun figure ce qu’un scanner y lit.",
    ),
    more_title="Niveaux de correction, et codes construits autrement",
    level="niveau {level} : {codewords} mots de correction",
)

# The sheet in Dutch.
DUTCH = Words(
    title="PDF417-codes, getekend als gestapelde streepjes",
    lines=(
        "Een PDF417-code is een stapel rijen streepjes boven elkaar, en hij bevat een heel",
        "formulier in plaats van een getal. Onder elke code wat een scanner leest.",
    ),
    more_title="Correctieniveaus, en codes op andere manieren opgebouwd",
    level="niveau {level}: {codewords} correctiecodewoorden",
)

# The sheet in Portuguese.
PORTUGUESE = Words(
    title="Códigos PDF417, desenhados como barras empilhadas",
    lines=(
        "Um código PDF417 é feito de filas de barras empilhadas e guarda",
        "um formulário inteiro e não um número. Por baixo de cada um, o que um leitor lê.",
    ),
    more_title="Níveis de correção, e códigos construídos de outras formas",
    level="nível {level}: {codewords} palavras de correção",
)

# The sheet in Italian.
ITALIAN = Words(
    title="Codici PDF417, disegnati come barre sovrapposte",
    lines=(
        "Un codice PDF417 è fatto di file di barre sovrapposte, e contiene un intero",
        "modulo anziché un numero. Sotto ciascuno, ciò che legge uno scanner.",
    ),
    more_title="Livelli di correzione, e codici costruiti in altri modi",
    level="livello {level}: {codewords} parole di correzione",
)

# The sheet in Spanish.
SPANISH = Words(
    title="Códigos PDF417, dibujados como barras apiladas",
    lines=(
        "Un código PDF417 son filas de barras apiladas unas sobre otras, y guarda un",
        "formulario entero y no un número. Debajo de cada uno, lo que lee un escáner.",
    ),
    more_title="Niveles de corrección, y códigos construidos de otras formas",
    level="nivel {level}: {codewords} palabras de corrección",
)

# The sheet in German.
GERMAN = Words(
    title="PDF417-Codes, als gestapelte Balken gezeichnet",
    lines=(
        "Ein PDF417-Code besteht aus übereinandergestapelten Balkenreihen und fasst",
        "ein ganzes Formular statt einer Zahl. Darunter steht, was ein Scanner liest.",
    ),
    more_title="Korrekturstufen und anders gebaute Codes",
    level="Stufe {level}: {codewords} Korrekturcodewörter",
)

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


def head(content, handle, words) -> None:
    """Draw the heading, and the lines under it that say what the page is for."""
    content.draw_text(handle, HEADING, MARGIN, HEAD_TOP, words.title)

    y = HEAD_TOP - HEAD_GAP
    for line in words.lines:
        content.draw_text(handle, BODY, MARGIN, y, line)
        y -= LINE_STEP



def levelled() -> list[tuple[hqf_pdf.Pdf417, int]]:
    """The codes of the second page: one at level 0, one handed over as
    UTF-8 bytes that name their character set, four built other ways, and one at level
    8. Each comes with the level it was built at."""
    return [
        (hqf_pdf.Pdf417(LEVELLED[0], level=0), 0),
        (
            hqf_pdf.Pdf417(LEVELLED[1].encode(), level=5, charset=hqf_pdf.Charset.UTF_8),
            5,
        ),
        (hqf_pdf.Pdf417(LEVELLED[2], columns=3), 2),
        (hqf_pdf.Pdf417(LEVELLED[3].encode()), 2),
        (hqf_pdf.Pdf417(LEVELLED[4].encode(), level=3), 3),
        (hqf_pdf.Pdf417(LEVELLED[5].encode(), columns=5), 2),
        (hqf_pdf.Pdf417(LEVELLED[6].encode(), columns=12, level=8), 8),
    ]


def levelled_page(handle, words) -> hqf_pdf.Page:
    """The second page: the codes of `levelled` one above the other, each with its
    payload and its level under it, under the page's heading.

    One column: a decoder reads codes set side by side less surely than codes set one
    above the other."""
    content = hqf_pdf.Content()
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    content.draw_text(handle, HEADING, MARGIN, HEAD_TOP, words.more_title)

    quiet = hqf_pdf.Pdf417.quiet_zone() * SMALL_MODULE
    aspect = hqf_pdf.Pdf417.row_aspect()
    top = HEAD_TOP - 40.0
    for (code, level), carried in zip(levelled(), LEVELLED):
        width = code.width * SMALL_MODULE
        height = code.height * SMALL_MODULE * aspect
        foot = top - height
        left = MARGIN
        content.draw_pdf417(code, left + quiet, foot, width, height)
        said = words.level.replace("{level}", str(level)).replace(
            "{codewords}", str(hqf_pdf.Pdf417.correction_codewords(level))
        )
        for line, drop in ((carried, 10.0), (said, 19.0)):
            content.draw_text(handle, 7.0, left + quiet, foot - drop, line)
        top = foot - (quiet * 2.0 + 30.0)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    return page


def dark_modules(code: hqf_pdf.Pdf417) -> str:
    """How many of `code`'s modules are dark, out of how many, as the terminal says it."""
    dark = sum(
        1
        for row in range(code.height)
        for column in range(code.width)
        if code.is_dark(row, column)
    )
    return f"{code.height} rows of {code.width} modules, {dark} of them dark"


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", words.title)

    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    content = hqf_pdf.Content()
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    head(content, handle, words)

    quiet = hqf_pdf.Pdf417.quiet_zone() * MODULE
    aspect = hqf_pdf.Pdf417.row_aspect()
    left = MARGIN
    top = TOP
    for carried in CARRIED:
        code = hqf_pdf.Pdf417(carried, columns=COLUMNS)
        width = code.width * MODULE
        # A module is drawn taller than it is wide, so a row is that much deeper than a
        # module is across.
        height = code.height * MODULE * aspect

        # The quiet zone is the caller's: the code is drawn that far in, and nothing
        # else is drawn beside it.
        content.draw_pdf417(code, left + quiet, top, width, height)
        print(dark_modules(code))
        content.draw_text(handle, 8.0, left + quiet, top - 12.0, carried)

        top -= height + quiet * 2.0 + 36.0

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)
    document.add_page(levelled_page(handle, words))

    written = document.write(out)
    print(f"wrote {out} ({written} bytes)")


if __name__ == "__main__":
    main()
