"""Barcodes for product labels: Code 128 (any text, read by every scanner) drawn as SVG, and in-store EAN-13 numbers.

In-store numbers start with 2 (the GS1 range kept for a shop's own use), so they never clash with a manufacturer's
barcode printed on the goods.
"""
from markupsafe import Markup

# Code 128 bar patterns (widths of bar, space, bar, space, bar, space), index = symbol value
PATTERNS = [
    "212222", "222122", "222221", "121223", "121322", "131222", "122213", "122312", "132212", "221213",
    "221312", "231212", "112232", "122132", "122231", "113222", "123122", "123221", "223211", "221132",
    "221231", "213212", "223112", "312131", "311222", "321122", "321221", "312212", "322112", "322211",
    "212123", "212321", "232121", "111323", "131123", "131321", "112313", "132113", "132311", "211313",
    "231113", "231311", "112133", "112331", "132131", "113123", "113321", "133121", "313121", "211331",
    "231131", "213113", "213311", "213131", "311123", "311321", "331121", "312113", "312311", "332111",
    "314111", "221411", "431111", "111224", "111422", "121124", "121421", "141122", "141221", "112214",
    "112412", "122114", "122411", "142112", "142211", "241211", "221114", "413111", "241112", "134111",
    "111242", "121142", "121241", "114212", "124112", "124211", "411212", "421112", "421211", "212141",
    "214121", "412121", "111143", "111341", "131141", "114113", "114311", "411113", "411311", "113141",
    "114131", "311141", "411131", "211412", "211214", "211232", "2331112",
]
START_B, START_C, CODE_B, CODE_C, STOP = 104, 105, 100, 99, 106


def _values(text):
    """Symbol values for text, using code C (digit pairs) for long digit runs so numbers print compactly."""
    if len(text) >= 4 and text.isdigit() and len(text) % 2 == 0:
        return [START_C] + [int(text[i:i + 2]) for i in range(0, len(text), 2)]
    vals = [START_B]
    for ch in text:
        o = ord(ch)
        if not 32 <= o <= 126:
            raise ValueError("Code 128 prints letters, digits and common symbols only.")
        vals.append(o - 32)
    return vals


def modules(text):
    """The barcode as a list of (is_bar, width in modules)."""
    vals = _values(text)
    check = (vals[0] + sum(i * v for i, v in enumerate(vals[1:], 1))) % 103
    out = []
    for v in vals + [check, STOP]:
        for i, w in enumerate(PATTERNS[v]):
            out.append((i % 2 == 0, int(w)))
    return out


def svg(text, height=40, module=1.4, show_text=True):
    """An inline SVG of the barcode with 10-module quiet zones."""
    text = str(text or "").strip()
    if not text:
        return Markup("")
    try:
        mods = modules(text)
    except ValueError:
        return Markup("")
    quiet = 10
    width = (sum(w for _, w in mods) + 2 * quiet) * module
    x = quiet * module
    rects = []
    for bar, w in mods:
        if bar:
            rects.append(f'<rect x="{x:.2f}" y="0" width="{w * module:.2f}" height="{height}"/>')
        x += w * module
    th = 12 if show_text else 0
    label = (f'<text x="{width / 2:.1f}" y="{height + 11}" text-anchor="middle" font-size="10" '
             f'font-family="monospace">{_esc(text)}</text>') if show_text else ""
    return Markup(f'<svg class="barcode" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width:.1f} {height + th}" '
                  f'width="{width:.1f}" height="{height + th}" role="img" aria-label="{_esc(text)}">'
                  f'<g fill="#000">{"".join(rects)}</g>{label}</svg>')


def _esc(s):
    return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")


def ean13_check(d12):
    s = sum(int(c) * (3 if i % 2 else 1) for i, c in enumerate(d12))
    return str((10 - s % 10) % 10)


def in_store_ean(product_id):
    """A unique in-store EAN-13 for a product: 2 + 0 + product id padded to 10 digits + check digit."""
    d12 = f"20{product_id:010d}"
    return d12 + ean13_check(d12)
