
from core.utils.packages import application, session
from core.utils.view_class_container_fields import get_clazz_fields
from flask import render_template, request, send_from_directory


def printPDF():
    import ast

    if request.method == "GET":
        classid = request.args.get('classid')
        clasname = application.getClazzName(int(classid))
        rowList = request.args.getlist('rowId')
        table_size = request.args.getlist('total')
        classfields = get_clazz_fields(clasname)
        action = "printPDF"

        if classid:
            return render_template("backend/interface/scopeDataAction.html", rowList=rowList, list_size=len(rowList), classid=clasname, table_size=table_size, action=action)
        else:
            return "Error: Los datos recibidos no son válidos.", 400
    else:
        classid = request.form.get("classid")
        export_scope = request.form.get("export_scope")
        classfields = get_clazz_fields(classid)

        if export_scope == "all_data":
            query = session.newQuery(classid)
            table = query.getRecordsFromSession()
        else:
            objList = request.form.getlist("rowList")

            if objList:
                strList = objList[0] 
                
                try:
                    lista_de_strings = ast.literal_eval(strList)
                    
                    # 4. Convertir cada ID a entero
                    lista_de_enteros = [int(item) for item in lista_de_strings]
                    
                except (ValueError, SyntaxError) as e:
                        # Esto captura errores si la cadena no es una lista válida de Python
                        print(f"Error al evaluar la estructura de datos: {e}")
                        lista_de_enteros = []
                    
            
            query = session.newQuery(classid)
            table = query.getRecords(lista_de_enteros)
        print(f"Exporting {len(table)} records for class ID {classid}")

        from core.utils.packages.engine import toPdf
        filename = f"export_{application.getClazzName(classid)}"
        #return render_template("backend/export/object.html", table=table,fields=classfields)
        html = render_template("backend/export/object.html", table=table,fields=classfields)
        pdfUrl = toPdf(html, filename)
        print(f"PDF generated and saved at {pdfUrl}")
            # Enviar el archivo de forma segura
        return send_from_directory(
            directory=pdfUrl[0],
            path=pdfUrl[1],
            as_attachment=True  # fuerza descarga
        )

extraActions = {"printPDF":printPDF}