"""Generate fictional print references. Requires ReportLab 5.0.1 and pdftoppm."""
import csv
from pathlib import Path
import subprocess

from reportlab.lib.units import mm
from reportlab.pdfgen.canvas import Canvas

OUT = Path(__file__).resolve().parent
FRAME = (50, 30)
MARGIN, GAP = 10, 4


def draw_label(pdf, x, y, code, product):
    """Place one fixed-size Frame; x and y are its lower left in mm."""
    x, y = x * mm, y * mm
    pdf.setFillColorRGB(.92, .95, .91)
    pdf.rect(x, y, FRAME[0] * mm, FRAME[1] * mm, fill=1, stroke=0)
    pdf.setFillColorRGB(.16, .31, .26)
    pdf.rect(x, y + 22 * mm, 50 * mm, 8 * mm, fill=1, stroke=0)
    pdf.setFillColorRGB(1, 1, 1)
    pdf.setFont('Helvetica-Bold', 8)
    pdf.drawString(x + 3 * mm, y + 25 * mm, 'FABLE / PAPER GOODS')
    pdf.setFillColorRGB(.12, .21, .17)
    pdf.setFont('Helvetica-Bold', 13)
    pdf.drawString(x + 3 * mm, y + 13 * mm, product)
    pdf.setFont('Courier', 9)
    pdf.drawString(x + 3 * mm, y + 5 * mm, code)


def generate():
    items = [f'{color} {item}' for color in ('Moss', 'Fern', 'Flax', 'Clay', 'Sage')
             for item in ('Folio', 'Journal', 'Cards', 'Planner', 'Notepad')]
    rows = [(f'FP-{i:03}', item) for i, item in enumerate(items, 1)]
    with (OUT / 'data.csv').open('w', newline='', encoding='utf-8') as data:
        writer = csv.writer(data)
        writer.writerow(['ItemCode', 'Product'])
        writer.writerows(rows)

    for name, w, h in [('a4', 297, 210), ('letter', 215.9, 279.4)]:
        cols, lines = [int((size - 2*MARGIN + GAP) // (frame + GAP))
                       for size, frame in zip((w, h), FRAME)]
        path = OUT / f'{name}.pdf'
        pdf = Canvas(str(path), pagesize=(w * mm, h * mm), invariant=1, pageCompression=0)
        pdf.setTitle(f'Fable Paper Goods - 50 x 30 mm labels on {name.upper()}')
        for i, record in enumerate(rows):
            slot = i % (cols * lines)
            if i and not slot:
                pdf.showPage()
            row, col = divmod(slot, cols)
            draw_label(pdf, MARGIN + col * (FRAME[0] + GAP),
                       h - MARGIN - FRAME[1] - row * (FRAME[1] + GAP), *record)
        pdf.save()
        subprocess.run(['pdftoppm', '-png', '-singlefile', '-f', '1', '-r', '72',
                        str(path), str(OUT / name)], check=True)


if __name__ == '__main__':
    generate()
