from django.views.decorators.http import require_GET
from django.http import JsonResponse, Http404, HttpResponse, HttpResponseBadRequest
from .printing import print_cb

from extras.models import CustomField
from .models import TagidCustomField
import random



@require_GET
def cf_tagid_test_generate(request, field_id:int):
    """
    Génère une valeur de test: prefix + length + suffix pour le CustomField `field_slug`,
    puis REDIRIGE vers l'URL `next` (par défaut '/'), en ajoutant ?field=<slug>&gen=<valeur>.
    """
    cf = CustomField.objects.filter(id=field_id).only("id", "name", "type").first()
    if not cf:
        raise Http404("Il n'y a pas de champs personnalisés TagID.")

    cfg = TagidCustomField.objects.filter(tag_id=cf).first()
    prefix = (cfg.prefix if cfg else "")
    suffix = (cfg.suffix if cfg else "")
    length = (cfg.length if cfg else 6)

    ref = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    # Ajout des minuscules si autorisé
    # if not prohibit_lowercase:
    #     ref += "abcdefghijklmnopqrstuvwxyz"

    # Génération du tag
    content = prefix
    for _ in range(length):
        content += random.choice(ref)
    content += suffix

    return HttpResponse(content)


@require_GET
def print_cb_view(request, field_id:int):
    
    cfg = TagidCustomField.objects.filter(tag_id=field_id).first()
    if not cfg:
        raise Http404("Il n'y a pas de champs personnalisés TagID.")

    printer_name = cfg.printer_name 
    printer_options = cfg.printer_opt 
    cups_host = cfg.cups_host 
    printer_count = cfg.printer_count 

    printer_options = printer_options.split('/')

    value = (request.GET.get("value") or "").strip()
    # if not value:
    #     return HttpResponseBadRequest("Missing value")
    
    out, code = print_cb(
        value,
        printer_count,
        printer_name,
        cups_host,
        printer_options
    )
    return JsonResponse({"ok": code == 0, "code": code, "output": out})