from io import BytesIO
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
import subprocess

# chemins par défaut vers les polices (mets tes TTF ici)
HERE = Path(__file__).resolve()
PLUGIN_ROOT = HERE.parents[1]                 
FONTS_DIR = PLUGIN_ROOT / "netbox_tag_id/fonts"             

FONT_CB_DEFAULT  = str(FONTS_DIR / "LibreBarcode39ExtendedText.ttf")
FONT_MSG_DEFAULT = str(FONTS_DIR / "Roboto-Bold.ttf")
  
def print_cb(value:str,count, printer: str, cups_host,options):
    margin: int = 8
    font_size: int = 40
    msg: str = "Ne pas enlever"   

    """
    Génère un PNG (Code39 via police LibreBarcode) + 'msg',
    puis imprime via CUPS (lp). Renvoie (lignes_sortie, code_retour).
    """
    if not value:
        return (["empty value"], 2)


    # 1) charger polices
    font_cb  = ImageFont.truetype(FONT_CB_DEFAULT, font_size)
    font_msg = ImageFont.truetype(FONT_MSG_DEFAULT, font_size // 2)

    # Code 39: start/stop par *
    barcode_text = f"*{value}*"

    # 2) mesurer
    tmp = Image.new("RGB", (10, 10))
    d = ImageDraw.Draw(tmp)

    l,t,r,b = d.textbbox((0,0), barcode_text, font=font_cb)
    w_cb, h_cb = (r-l), (b-t)

    l,t,r,b = d.textbbox((0,0), msg, font=font_msg)
    w_msg, h_msg, t_msg = (r-l), (b-t), t  

    width  = w_cb + margin*2
    height = int((-t_msg)*1.5 + h_cb + margin*2)
    height += 50
    

    # 3) dessiner
    img = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(img)

    # message centré
    x_msg = margin + (w_cb - w_msg)//2
    y_msg = margin - t_msg
    y_msg += 10
    draw.text((x_msg, y_msg), msg, fill="black", font=font_msg)

    # code-barres
    x_cb = margin
    y_cb = margin - int(t_msg*1.5) - d.textbbox((0,0), barcode_text, font=font_cb)[1]
    y_cb += 45
    draw.text((x_cb, y_cb), barcode_text, fill="black", font=font_cb)

    # 4) PNG en mémoire
    buf = BytesIO()
    img.save(buf, format="PNG", compress_level=9)
    png_bytes = buf.getvalue()

    # 5) lp (sans shell)
    cmd = ["lp"]
    #cmd += ["-h", "cups:631"]
    if cups_host:
        cmd += ["-h", cups_host]
    if printer:
        cmd += ["-d", printer]
    for opt in options:
        cmd += ["-o", opt]

    # if pagesize:
    #     cmd += ["-o", f"PageSize=Custom.{pagesize}"]
    if count and count != 1:
        cmd += ["-n", str(int(count))]

    print(cmd)
    proc = subprocess.run(cmd, input=png_bytes, capture_output=True)
    out = (proc.stdout or b"").decode(errors="ignore").splitlines()
    err = (proc.stderr or b"").decode(errors="ignore").splitlines()

    
    return (out + err, proc.returncode)