
from core.utils.packages import application, session, engine
from core.utils.packages.engine import traceError
from flask import Blueprint, render_template, request, flash, redirect, url_for, current_app, jsonify
from flask import session as Session
from flask_login import login_required
from datetime import datetime, timedelta, timezone
import json
from werkzeug.utils import secure_filename
import os
import requests
import hashlib


blueprintname = Blueprint("custom", __name__)
slug = "c"

@blueprintname.route(f'/{slug}/')
def index():
    return "Custom URLs"


@blueprintname.route(f'/admin/stats')
@traceError
@login_required
def general_stats():
    return render_template('backend/custom/statscollection.html')

@blueprintname.route(f'/admin/update')
@traceError
def general_update():
    """
    query = session.newQuery("object").getTable()
    for record in query:
        record = record.getORMRecord()
        methods = ["helper_qtyImage","helper_qtySD","helper_qtyHD"]
        for method in methods:
            helper_function = getattr(record, method)
            if callable(helper_function):
                print(f"Calling helper function: {helper_function}")
                result = helper_function()
    print("Actualizados")
    """
    from draft.tesauros.object import fieldsImport
    rows = engine.readCSV("draft/importar/objects.csv")
    for key, value in fieldsImport.items():
        
        error = ""
        for row in rows:
            id = int(row["Id"])
            head = row[key] if row[key] else None
            
            try:
                record = session.getRecord("object",id)
                if head and head != "false" and head != "true":
                    record.store(value,head)
                elif  head == "true":
                    record.store(value,True)
                #if created_at:
                #    created_at = convert_timestamp_to_utc(created_at)
                #    record.store("created_at",created_at)
                #if createdby_id:
                #        record.store("createdby_id",createdby_id)

            except Exception as e:
                print(f"Error en row {id}: {e}")
                error += f"Error {id}: {e} \n"
                pass
    print("Importación concluída correctamente")
    return  f"Importado correctamente: {error}"
'''
@blueprintname.route(f'/{slug}/pdf')
def to_pdf():
    from flask import send_from_directory
    from core.utils.view_class_container_fields import get_clazz_fields

    headers = ["IMG","No Acc","Título","Id"]
    fields = ["featuredImage","accessionNumber","title","id"]
    classfields = get_clazz_fields(1)
    q = session.newQuery(1)
    table = q.getRecords([176236,176287,176228])
    html = render_template("backend/export/table.html", table=table,headers=headers,fields=fields,classfields=classfields)

    # PDF path to save
    filename = "table"
    pdfUrl = engine.toPdf(html, filename)
    # Generate PDF
    if pdfUrl:
        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
        )

    else:
        return "Export generation failed"
'''


@blueprintname.route(f'/import/measurements')
@traceError
def import_measurements():
    rows = engine.readCSV("draft/importar/measurements.csv")
    error = ""
    guardado = None
    for row in rows:
        id = int(row["id"])
        circumference = row["Circumferencia / Perímetro"] if row["Circumferencia / Perímetro"] else None
        contour = row["Contorno"] if row["Contorno"] else None
        depth = row["Profundidad"] if row["Profundidad"] else None
        diameter = row["Diámetro"] if row["Diámetro"] else None
        exactApprox = row["Exacto / Aproximado"] if row["Exacto / Aproximado"] else None
        height = row["Altura"] if row["Altura"] else None
        insideSize = row["Parte Interna"] if row["Parte Interna"] else None
        item = row["Item"] if row["Item"] else None
        label = row["Resumen"] if row["Resumen"] else None
        length = row["Largo"] if row["Largo"] else None
        object_id = row["Object"] if row["Object"] else None
        other = row["Otro"] if row["Otro"] else None
        outsideSize = row["Parte Externa"] if row["Parte Externa"] else None
        size = row["Tamaño"] if row["Tamaño"] else None
        thickness = row["Grosor"] if row["Grosor"] else None
        units = row["Unidades"] if row["Unidades"] else None
        volume = row["Volumen"] if row["Volumen"] else None
        weight = row["Peso"] if row["Peso"] else None
        weightUnit = row["Unidad (Peso)"] if row["Unidad (Peso)"] else None
        width = row["Ancho"] if row["Ancho"] else None
        withFrame = True if row["Con Marco"] else False

        try:
            record = session.newRecord("measurement")
            record.store("id",id)
            record.store("circumference",circumference)
            record.store("contour",contour)
            record.store("depth",depth)
            record.store("diameter",diameter)
            record.store("exactApprox",exactApprox)
            record.store("height",height)
            record.store("insideSize",insideSize)
            record.store("item",item)
            record.store("label",label)
            record.store("length",length)
            record.store("object_id",object_id)
            record.store("other",other)
            record.store("outsideSize",outsideSize)
            record.store("size",size)
            record.store("thickness",thickness)
            record.store("units",units)
            record.store("volume",volume)
            record.store("weight",weight)
            record.store("weightUnit",weightUnit)
            record.store("width",width)
            record.store("withFrame",withFrame)
            guardado = record.save()
        except Exception as e:
            print(f"Error en row {id}: {e}")
            error += f"Error {id}: {e} \n"
            pass
    print("Importación concluída correctamente")
    return  f"Importado correctamente {id} = {guardado}: {error}"


from datetime import datetime
from datetime import timezone

def convert_timestamp_to_utc(timestamp_str):
    """
    Convierte la cadena de formato 'YYYYMMDD_HHMMSSms' a un objeto datetime en UTC.
    """
    # 1. Adaptar la cadena para cumplir con el estándar de microsegundos (%f)
    # Tu formato es YYYYMMDD_HHMMSSms. Necesitamos YYYYMMDD_HHMMSSfff000 (6 dígitos)
    # Si la cadena original es '20221031_204605000', tomamos hasta el segundo (204605) y 
    # asumimos que '000' son milisegundos, rellenando a 6 ceros.
    
    # Si el formato es estrictamente YYYYMMDD_HHMMSS000 (9 dígitos después del _)
    date_part = timestamp_str[:8] # 20221031
    time_part = timestamp_str[9:15] # 204605
    ms_part = timestamp_str[15:] # 000 (o 000000 si fueran microsegundos)
    
    # El patrón de formato para strptime (el '000' lo tratamos como microsegundos, o lo descartamos)
    format_pattern = "%Y%m%d_%H%M%S"
    
    # Intentamos primero con microsegundos (si el formato es consistente)
    # Si el CSV es consistentemente YYYYMMDD_HHMMSSNNN, el patrón correcto es:
    if len(timestamp_str) == 18:
        # Esto asume 3 dígitos después del segundo son milisegundos (Ej: 204605000)
        # Lo más seguro es descartar los últimos 3 dígitos si solo necesitas segundos
        format_pattern = "%Y%m%d_%H%M%S"
        time_with_seconds = timestamp_str[:15]
        dt_obj = datetime.strptime(time_with_seconds, format_pattern)
    elif len(timestamp_str) == 21:
        # Asume formato completo con microsegundos (YYYYMMDD_HHMMSS######)
        format_pattern = "%Y%m%d_%H%M%S%f"
        dt_obj = datetime.strptime(timestamp_str, format_pattern)
    else:
        # Opción más segura: ignorar los milisegundos
        format_pattern = "%Y%m%d_%H%M%S"
        dt_obj = datetime.strptime(timestamp_str[:15], format_pattern)


    # 2. Asignar la zona horaria UTC (critical para tu modelo)
    # Tu modelo espera un objeto aware: created_at = db.Column(..., default=lambda: datetime.now(timezone.utc))
    dt_utc_aware = dt_obj.replace(tzinfo=timezone.utc)
    
    return dt_utc_aware


@blueprintname.route(f'/import/objectfields')
@traceError
def import_objectsfields():
    rows = engine.readCSV("draft/importar/objects.csv")
    error = ""
    for row in rows:
        id = int(row["Id"])
        updated_at = row["Fecha de actualización"] if row["Fecha de actualización"] else None
        created_at = row["Fecha de ingreso en la base de datos"] if row["Fecha de ingreso en la base de datos"] else None
        createdby_id = row["Registrador"] if row["Registrador"] else None
        
        costAdmin = row["Costo"] if row["Costo"] else None
        costUSDAdmin = row["Costo USD"] if row["Costo USD"] else None
        conservationStateSpecify = row["Estado de Conservación (Especificar)"] if row["Estado de Conservación (Especificar)"] else None
        dateEra = row["Fecha / Época"] if row["Fecha / Época"] else None
        acquisitionDate = row["Fecha de adquisición"] if row["Fecha de adquisición"] else None
        appraisalDate = row["Fecha de Avalúo"] if row["Fecha de Avalúo"] else None
        creationDate = row["Fecha de Creación"] if row["Fecha de Creación"] else None
        ingressDate = row["Fecha de Ingreso"] if row["Fecha de Ingreso"] else None
        partOf = row["Forma parte de"] if row["Forma parte de"] else None
        acquisitionHistory = row["Información de adquisición"] if row["Información de adquisición"] else None
        insurerName = row["Nombre de Asegurador"] if row["Nombre de Asegurador"] else None
        observations = row["Observaciones_2"] if row["Observaciones_2"] else None
        purchasePrice = row["Precio de Compra"] if row["Precio de Compra"] else None
        salePrice = row["Precio de venta"] if row["Precio de venta"] else None
        insuranceResponsible = row["Responsable de la prima"] if row["Responsable de la prima"] else None
        insurancePercent = row["Seguro en Porcentaje"] if row["Seguro en Porcentaje"] else None
        insuranceAmountAdmin = row["Seguro en Valor"] if row["Seguro en Valor"] else None
        typeAcquisition = row["Tipo de Adquisición"] if row["Tipo de Adquisición"] else None
        insuranceValue = row["Valor del Seguro"] if row["Valor del Seguro"] else None
        valueUSDAdmin = row["Valor en USD"] if row["Valor en USD"] else None
        estimatedValue = row["Valor Estimado"] if row["Valor Estimado"] else None
        

        try:
            record = session.newRecord("object")
            #    record.store("created_at",created_at)
            #if createdby_id:
            #        record.store("createdby_id",createdby_id)
            
            if id:
                record.store("id",id)
            if costAdmin:
                record.store("costAdmin",costAdmin)
            if costUSDAdmin:
                record.store("costUSDAdmin",costUSDAdmin)
            if conservationStateSpecify:
                record.store("conservationStateSpecify",conservationStateSpecify)
            if dateEra:
                record.store("dateEra",dateEra)
            if acquisitionDate:
                record.store("acquisitionDate",acquisitionDate)
            if appraisalDate:
                record.store("appraisalDate",appraisalDate)
            if creationDate:
                record.store("creationDate",creationDate)
            if ingressDate:
                record.store("ingressDate",ingressDate)
            if partOf:
                record.store("partOf",partOf)
            if acquisitionHistory:
                record.store("acquisitionHistory",acquisitionHistory)
            if insurerName:
                record.store("insurerName",insurerName)
            if observations:
                record.store("observations",observations)
            if purchasePrice:
                record.store("purchasePrice",purchasePrice)
            if salePrice:
                record.store("salePrice",salePrice)
            if insuranceResponsible:
                record.store("insuranceResponsible",insuranceResponsible)
            if insurancePercent:
                record.store("insurancePercent",insurancePercent)
            if insuranceAmountAdmin:
                record.store("insuranceAmountAdmin",insuranceAmountAdmin)
            if typeAcquisition:
                record.store("typeAcquisition",typeAcquisition)
            if insuranceValue:
                record.store("insuranceValue",insuranceValue)
            if valueUSDAdmin:
                record.store("valueUSDAdmin",valueUSDAdmin)
            if estimatedValue:
                record.store("estimatedValue",estimatedValue)
            if created_at:
                created_at = convert_timestamp_to_utc(created_at)
                record.store("created_at",created_at)
            if updated_at:
                updated_at = convert_timestamp_to_utc(updated_at)
                record.store("updated_at",updated_at)
            record.save()

        except Exception as e:
            print(f"Error en row {id}: {e}")
            error += f"Error {id}: {e} \n"
            pass
    print("Importación concluída correctamente")
    return  f"Importado correctamente: {error}"



'''
@blueprintname.route(f'/import/creators')
@traceError
def import_creators():
    #from draft.measurement import dict_fields
    #application.import_clazz(dict_fields)
    rows = engine.readCSV("draft/importar/creators.csv")
    
    for row in rows:
        fullname = row["Nombre Completo"] if row["Nombre Completo"] else None
        objectQty = int(row["Cantidad de Objetos"]) if row["Cantidad de Objetos"] else None
        alias = row["Alias / Seudónimo"] if row["Alias / Seudónimo"] else None
        lastname = row["Apellido (s)"] if row["Apellido (s)"] else None
        appreticeOf = row["Aprendiz de"] if row["Aprendiz de"] else None
        authorCode = row["Author Code"] if row["Author Code"] else None
        biography = row["Biografía"] if row["Biografía"] else None
        deceased = row["Deceso (Año)"] if row["Deceso (Año)"] else None
        gender = row["Género"] if row["Género"] else None
        id = int(row["Id"]) if row["Id"] else None
        placeDeceased = row["Lugar de Deceso"] if row["Lugar de Deceso"] else None
        placeBirth = row["Lugar de Nacimiento"] if row["Lugar de Nacimiento"] else None
        observations = row["Más Información"] if row["Más Información"] else None
        bornYear = row["Nacimiento (Año)"] if row["Nacimiento (Año)"] else None
        firstname = row["Nombre (s)"] if row["Nombre (s)"] else None
        collectiveName = row["Nombre de Colectivo o Empresa"] if row["Nombre de Colectivo o Empresa"] else None
        country = row["País"] if row["País"] else None
        disciple = row["Seguidor de"] if row["Seguidor de"] else None
        tags = row["Tags / Metadatos"] if row["Tags / Metadatos"] else None
        workshop = row["Taller / Estudio"] if row["Taller / Estudio"] else None
        atelier = row["Taller de"] if row["Taller de"] else None
        textsearch = row["Text Search"] if row["Text Search"] else None
        type = row["Tipo de Autor"] if row["Tipo de Autor"] else None

        try:
            newRecord = session.newRecord("creator")
            if fullname:
                newRecord.store("fullname",fullname)
            if objectQty:
                newRecord.store("objectQty",objectQty)
            if alias:
                newRecord.store("alias",alias)
            if lastname:
                newRecord.store("lastname",lastname)
            if appreticeOf:
                newRecord.store("appreticeOf",appreticeOf)
            if authorCode:
                newRecord.store("authorCode",authorCode)
            if biography:
                newRecord.store("biography",biography)
            if deceased:
                newRecord.store("deceased",deceased)
            if gender:
                newRecord.store("gender",gender)
            if id:
                newRecord.store("id",id)
            if placeDeceased:
                newRecord.store("placeDeceased",placeDeceased)
            if placeBirth:
                newRecord.store("placeBirth",placeBirth)
            if observations:
                newRecord.store("observations",observations)
            if bornYear:
                newRecord.store("bornYear",bornYear)
            if firstname:
                newRecord.store("firstname",firstname)
            if collectiveName:
                newRecord.store("collectiveName",collectiveName)
            if country:
                newRecord.store("country",country)
            if disciple:
                newRecord.store("disciple",disciple)
            if tags:
                newRecord.store("tags",tags)
            if workshop:
                newRecord.store("workshop",workshop)
            if atelier:
                newRecord.store("atelier",atelier)
            if textsearch:
                newRecord.store("textsearch",textsearch)
            if type:
                newRecord.store("type",type)
            newRecord.save()
        except Exception as e:
            print(f"Error en row {id}: {e}")
            pass
    print("Importación concluída correctamente")
    return "Importado correctamente"
'''
@blueprintname.route(f'/import/locationlogs')
@traceError
def import_locationlogs():
    #from draft.measurement import dict_fields
    #application.import_clazz(dict_fields)
    rows = engine.readCSV("draft/importar/locations_monitor.csv")
    
    for row in rows:
        id = row["Identificador"]
        status = row["Estátus"] if row["Estátus"] else None
        exhibitionRoom = row["Sala de Exhibición"] if row["Sala de Exhibición"] else None
        storageNumber = row["Número de Almacenamiento"] if row["Número de Almacenamiento"] else None
        depositShelf = row["Estante"] if row["Estante"] else None
        information = row["Información"] if row["Información"] else None
        fromDate = row["De"] if row["De"] else None
        tillDate = row["Hasta"] if row["Hasta"] else None
        location_id = row["Ubicación"] if row["Ubicación"] else None
        detail = row["Detalle"] if row["Detalle"] else None
        object = row["Objeto"] if row["Objeto"] else None

        try:
            newRecord = session.newRecord("locationlog")
            if id:
                newRecord.store("id",id)
            if status:
                newRecord.store("status",status)
            if exhibitionRoom:
                newRecord.store("exhibitionRoom",exhibitionRoom)
            if storageNumber:
                newRecord.store("storageNumber",storageNumber)
            if depositShelf:
                newRecord.store("depositShelf",depositShelf)
            if information:
                newRecord.store("information",information)
            if fromDate:
                formatfromDate = engine.strToDate(fromDate,"%Y%m%d")
                newRecord.store("fromDate",formatfromDate)
            if tillDate:
                formattillDate = engine.strToDate(tillDate,"%Y%m%d")
                newRecord.store("tillDate",formattillDate)
            if location_id:
                newRecord.store("location_id",int(location_id))
            if detail:
                newRecord.store("detail",detail)
            if object:
                newRecord.store("object_id",int(object))
            newRecord.save()
        except Exception as e:
            print(f"Error en row {id}: {e}")
            pass
    print("Importación concluída correctamente")
    return "Importado correctamente"
'''
@blueprintname.route(f'/import/groups')
@traceError
def import_groups():
    rows = engine.readCSV("draft/importar/export_Relations.csv")
    
    for row in rows:
        name = row["Nombre"] if row["Nombre"] else None
        description = row["Descripción"] if row["Descripción"] else None
        typeSpecify = row["Especificar"] if row["Especificar"] else None
        type = row["Tipo de relación / grupo"] if row["Tipo de relación / grupo"] else None
        internalExternal = row["Exposición Interna o Externa"] if row["Exposición Interna o Externa"] else None
        itinerant = True if row["Itinerante"] == "true" else False
        dateStart = row["Inicia"] if row["Inicia"] else None
        dateDue = row["Finaliza"] if row["Finaliza"] else None
        id = int(row["Id"]) if row["Id"] else None


        try:
            newRecord = session.newRecord("objectgroup")
            if name:
                newRecord.store("name",name)
            if description:
                newRecord.store("description",description)
            if typeSpecify:
                newRecord.store("typeSpecify",typeSpecify)
            if type:
                newRecord.store("type",type)
            if internalExternal:
                newRecord.store("internalExternal",internalExternal)
            if itinerant:
                newRecord.store("itinerant",itinerant)
            if dateStart:
                newRecord.store("dateStart",dateStart)
            if dateStart:
                newRecord.store("dateDue",dateStart)
            if id:
                newRecord.store("id",id)
            newRecord.save()
        except Exception as e:
            print(f"Error en row {id}: {e}")
            pass
    print("Importación concluída correctamente")
    return "Importado correctamente"
'''
@blueprintname.route(f'/import/locations')
@traceError
def import_locations():
    #from draft.measurement import dict_fields
    #application.import_clazz(dict_fields)
    rows = engine.readCSV("draft/importar/locations.csv")
    for row in rows:
        id = int(row["Id"])
        name = row["Nombre"]
        objectsQty = int(row["Total Number of Objects"]) if row["Total Number of Objects"] else None
        position = row["Position"]

        try:
            newRecord = session.newRecord("location")
            newRecord.store("id",id)
            newRecord.store("name",name)
            newRecord.store("objectsQty",objectsQty)
            newRecord.store("position",position)
            newRecord.save()
        except Exception as e:
            print(f"Error en row {id}: {e}")
            pass
    print("Importación concluída correctamente")
    for row in rows:
        id = row["Id"]
        parent_id = row["Pertenece a"]
        if parent_id:
            parent_id = int(parent_id)
            try:
                newRecord = session.getRecord("location",int(id))
                newRecord.store("parent_id",parent_id)
            except Exception as e:
                print(f"Error en row {id}: {e}")
                pass
        else:
            parent_id = None
        
    print("Importación de relaciones concluída correctamente")
    return "Importado correctamente"
'''
@blueprintname.route(f'/import/tags')
@traceError
def import_tags():
    rows = engine.readCSV("draft/importar/export_Tags.csv")

    for row in rows:
        id = int(row["Id"])
        name = row["Tag"]

        try:
            newRecord = session.newRecord("tag")
            newRecord.store("id",id)
            newRecord.store("name",name)
            newRecord.save()
        except Exception as e:
            print(f"Error en row {id}: {e}")
            pass
    print("Importación concluída correctamente")

@blueprintname.route(f'/import/themes')
@traceError
def import_period():
    rows = engine.readCSV("draft/importar/export_Themes.csv")

    for row in rows:
        id = int(row["Id"])
        name = row["Nombre"]

        try:
            newRecord = session.newRecord("theme")
            newRecord.store("id",id)
            newRecord.store("name",name)
            newRecord.save()
        except Exception as e:
            print(f"Error en row {id}: {e}")
            pass
    print("Importación concluída correctamente")
'''
@blueprintname.route(f'/import/connectedfields')
@traceError
def import_connected():
    #rows = engine.readCSV("draft/importar/export_Themes.csv")
    from draft.tesauros.fields import category, material,period,type, technique, tags, author, collection, theme,  groups 
    from core.utils.db import db
    import json

    objects = session.newQuery("object")
    rows = objects.getTable()
    for object in rows:
        id = object.get("id")
        orm = object.getORMRecord()
        idstr = str(id)
        error = ""
        try:
            model_class = session.newQuery("category")
            if category.get(idstr) != "[]":
                listCat = json.loads(category.get(idstr))
                related_objects = model_class.getRecords(listCat)
                # limpiar y volver a asignar
                getattr(orm, "categoryList").clear()
                getattr(orm, "categoryList").extend(related_objects)
                db.session.commit()
        except Exception as e:
            print(e)
            error += f"Error {id} en categoría: {e} \n"
            pass
        try:
            model_class = session.newQuery("material")
            if material.get(idstr) != "[]":
                listCat = json.loads(material.get(idstr))
                related_objects = model_class.getRecords(listCat)
                # limpiar y volver a asignar
                getattr(orm, "materialsList").clear()
                getattr(orm, "materialsList").extend(related_objects)
                db.session.commit()
        except Exception as e:
            print(e)
            error += f"Error {id} en Material: {e} \n"
            pass
        
        try:
            model_class = session.newQuery("objectgroup")
            if groups.get(idstr) != "[]":
                listCat = json.loads(groups.get(idstr))
                related_objects = model_class.getRecords(listCat)
                # limpiar y volver a asignar
                getattr(orm, "objectGroup").clear()
                getattr(orm, "objectGroup").extend(related_objects)
                db.session.commit()
        except Exception as e:
            print(e)
            error += f"Error {id} en grupo: {e} \n"
            pass
        try:
            model_class = session.newQuery("styleperiod")
            if period.get(idstr) != "[]":
                listCat = json.loads(period.get(idstr))
                related_objects = model_class.getRecords(listCat)
                # limpiar y volver a asignar
                getattr(orm, "periods").clear()
                getattr(orm, "periods").extend(related_objects)
                db.session.commit()
        except Exception as e:
            print(e)
            error += f"Error {id} en periodo: {e} \n"
            pass
        try:
            model_class = session.newQuery("type")
            if type.get(idstr) != "[]":
                listCat = json.loads(type.get(idstr))
                related_objects = model_class.getRecords(listCat)
                # limpiar y volver a asignar
                getattr(orm, "objectTypeList").clear()
                getattr(orm, "objectTypeList").extend(related_objects)
                db.session.commit()
        except Exception as e:
            print(e)
            error += f"Error {id} en tipo: {e} \n"
            pass
        try:
            model_class = session.newQuery("technique")
            if technique.get(idstr) != "[]":
                listCat = json.loads(technique.get(idstr))
                related_objects = model_class.getRecords(listCat)
                # limpiar y volver a asignar
                getattr(orm, "methodsTechniquesList").clear()
                getattr(orm, "methodsTechniquesList").extend(related_objects)
                db.session.commit()
        except Exception as e:
            print(e)
            error += f"Error {id} en technica: {e} \n"
            pass
        """
        try:
            model_class = session.newQuery("tag")
            if tags.get(idstr) != "[]":
                listCat = json.loads(tags.get(idstr))
                related_objects = model_class.getRecords(listCat)
                # limpiar y volver a asignar
                getattr(orm, "tags").clear()
                getattr(orm, "tags").extend(related_objects)
                db.session.commit()
        except Exception as e:
            print(e)
            error += f"Error {id} en tag: {e} \n"
            pass
        try:
            if theme.get(idstr) != "":
                object.store("theme_id",int(theme.get(idstr)))
                
        except Exception as e:
            print(e)
            error += f"Error {id} en tema: {e} \n"
            pass
        try:
            if author.get(id):
                object.store("creator_id",int(author.get(id)))
                
        except Exception as e:
            print(e)
            error += f"Error {id} en tema: {e} \n"
            pass
        try:
            if collection.get(id):
                object.store("collection_id",int(collection.get(id)))
                
        except Exception as e:
            print(e)
            error += f"Error {id} en tema: {e} \n"
            pass
        """
    print("Importación concluída correctamente")
    """
    for row in rows:
        id = row["id"]
        parent_id = row["Estilos / Períodos"]
        if parent_id:
            parent_id = int(parent_id)
            try:
                newRecord = session.getRecord("styleperiod",int(id))
                newRecord.store("parent_id",parent_id)
            except Exception as e:
                print(f"Error en row {id}: {e}")
                pass
        else:
            parent_id = None
        
    print("Importación de relaciones concluída correctamente")
    """
    return "Importado correctamente"

"""
@blueprintname.route(f'/import/relations/')
@traceError
def importTesauros():
    from draft.importDef import updateParent
    from draft.importObject import fieldsRelation
    fieldsImport = fieldsRelation

    csvname = request.args.get("csvname")
    classname = request.args.get("classname")
    report_filename = request.args.get("report")
    return updateParent(csvname, classname, fieldsImport, report_filename)

@blueprintname.route(f'/import/clazzes/')
@traceError
def importObject():
    from draft.importDef import importCSV_with_report
    from draft.importObject import fieldsImportTesauro
    fieldsImport = fieldsImportTesauro

    csvname = request.args.get("csvname")
    classname = request.args.get("classname")
    report_filename = request.args.get("report")
    return importCSV_with_report(csvname, classname, fieldsImport, report_filename)
"""
@blueprintname.route(f'/import/images/')
@traceError
def importimgs():
    rows = engine.readCSV("draft/importar/images.csv")
    error = ""
    from core.models.develop.blob import Blob
    from core.utils.db import db
    for row in rows:
        id = int(row["Id"])
        pie = row["Pie de Imagen"]
        object = row["Objeto"]
        try:
            newRecord = session.newRecord("image")
            newRecord.store("id",id)
            newRecord.store("caption",pie)
            newRecord.store("object_id",object)

            try:
                #print(idobject)

                blob = Blob.query.get(id)
                if blob:
                        newRecord.store("image_id",id)
            except Exception as e:
                print(e)
                pass
            
            newRecord.save()
        except Exception as e:
            print(f"Error en row {id}: {e}")
    return "hola"


@blueprintname.route(f'/admin/imgstoblob')
@traceError
def convert_imgs():
    rows = engine.readCSV("draft/reporte_descargas.csv",delimiter=",")
    error = ""
    for row in rows:
        id = int(row["ID"])
        original_name = row["original_name"]
        mime_type = row["mime_type"]
        size = int(row["size"])
        
        try:
            from core.models.develop.blob import Blob
            from core.utils.db import db
            blob = Blob()
            blob.original_name = original_name
            blob.mime_type = mime_type
            blob.size = size
            blob.id = id
            db.session.add(blob)
            db.session.commit()
           


        except Exception as e:
            print(f"Error en row {id}: {e}")
            error += f"Error {id}: {e} \n"
            pass
    print("Importación concluída correctamente")
    return  f"Importado correctamente: {error}"