// A food plant's carton labels on a SATO printer (CL4NX, CT4-LX): the product, its GTIN, lot
// and best-before date as GS1-128, a QR code, a frame, printed in a run.
//
//   quillo run sbpl.qwe      then open http://localhost:8080/label
//   PRINTER_HOST=192.168.1.65 quillo run sbpl.qwe      and http://localhost:8080/print

use "sbpl.qwer"

let OPTIONS = { dpi: 203, width: 100, height: 70, speed: 4, darkness: 3, quantity: 12 }

fn carton(c) = [
    { box: true, x: 1, y: 1, width: 98, height: 68, thickness: 0.5 },
    { text: c.name, x: 4, y: 4, size: 6 },
    { text: `Lot ${c.lot}  Best before ${c.best_before}`, x: 4, y: 13, size: 3 },
    { line: true, x: 1, y: 19, width: 98, thickness: 0.4 },
    { barcode: "gs1_128", data: `(01)${c.gtin}(15)${c.bb}(10)${c.lot}`, x: 4, y: 24, height: 18, module: 2 },
    { barcode: "code128", data: c.sku, x: 4, y: 52, height: 8, module: 2, readable: false },
    { barcode: "qr", data: `https://food.example/lot/${c.lot}`, x: 76, y: 44, magnification: 4 },
]

let CARTON = { name: "Oat crackers 12 x 200 g", gtin: "09501101530003", lot: "L2610B", bb: "270430", best_before: "30.04.2027", sku: "OC-200-12" }

route GET /label = respond(200, sbpl_label(carton(CARTON), OPTIONS)?, { "content-type": "text/plain; charset=utf-8" })

route GET /saved = { bytes: sbpl_write(carton(CARTON), OPTIONS, "data/carton.sbpl")?, start: slice(sbpl_job(carton(CARTON), OPTIONS)?, 0, 8), bad: sbpl_label([{ barcode: "code128", data: "a>b" }], {}).error }

route GET /print {
    let host = env("PRINTER_HOST", null) ?? reply 503 "set PRINTER_HOST to the printer's address (host or host:port)"
    { sent: sbpl_send(carton(CARTON), OPTIONS, host, 5000)? }
}
