# Optimized Python Code
# Archivo: DMControllerPreheaterSQL.py
# Ruta: src\Consultas_SQL\Ventas\VentasEUA\DataMaster\DMControllerPreheaterSQL.py
# Lenguaje: Python


from Consultas_SQL.conexion import get_connection
def get_Controlador_del_precalentador():
    """Obtiene catalogo de controles desde la base de datos."""
    query = """
     SELECT
        CZE_ControllerPreheater.Item_preheater_volt, 
        CZE_ControllerPreheater.description, 
        CZE_ControllerPreheater.price, 
        CZE_ControllerPreheater.TechnicalSheet
    FROM
        CZE_ControllerPreheater
    """
    try:
        conn = get_connection()
        if not conn:
            raise ConnectionError("No se pudo establecer conexión con la base de datos")
        
        cursor = conn.cursor()
        cursor.execute(query)
        results = cursor.fetchall()
        
        # Aseguramos que las claves del diccionario coincidan con las usadas en el JavaScript
        return [{"Item_preheater_volt": row[0], "description": row[1], "price": row[2], "TechnicalSheet": row[3]} for row in results]
    except Exception as e:
        print(f"[Error inesperado] Error obteniendo breakers: {e}")
        return []
    finally:
        if conn:
            conn.close()
            

def item_exists(item):
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM CZE_ControllerPreheater WHERE Item_preheater_volt = ?", (item,))
        result = cursor.fetchone()
        return result
    finally:
        if conn:
            conn.close()

def insert_Controlador_del_precalentador(item, description, price, technicalSheet):
    """Inserta un nuevo breaker en la base de datos."""
    query = """
    INSERT INTO CZE_ControllerPreheater (Item_preheater_volt, description, price,TechnicalSheet)
    VALUES (?, ?, ?, ?)
    """
    try:
        conn = get_connection()
        if not conn:
            raise ConnectionError("No se pudo establecer conexión con la base de datos")
        
        cursor = conn.cursor()
        cursor.execute(query, (item, description, price, technicalSheet))
        
        conn.commit()
    except Exception as e:
        print(f"[Error inesperado] Error insertando breaker: {e}")
    finally:
        if conn:
            conn.close()
            
def update_Controlador_del_precalentador(item, description, price):
    """Actualiza un breaker en la base de datos."""
    query = """
    UPDATE CZE_ControllerPreheater
    SET description = ?, price = ?
    WHERE Item_preheater_volt = ?
    """
    try:
        conn = get_connection()
        if not conn:
            raise ConnectionError("No se pudo establecer conexión con la base de datos")
        
        cursor = conn.cursor()
        cursor.execute(query, (description, price, item))
        conn.commit()
    except Exception as e:
        print(f"[Error inesperado] Error actualizando breaker: {e}")
    finally:
        if conn:
            conn.close()
            
def delete_Controlador_del_precalentador(item):
    """Elimina un breaker de la base de datos."""
    query = """
    DELETE FROM CZE_ControllerPreheater
    WHERE Item_preheater_volt = ?
    """
    try:
        conn = get_connection()
        if not conn:
            raise ConnectionError("No se pudo establecer conexión con la base de datos")
        
        cursor = conn.cursor()
        cursor.execute(query, (item,))
        conn.commit()
    except Exception as e:
        print(f"[Error inesperado] Error eliminando el Control: {e}")
    finally:
        if conn:
            conn.close()

def searchitems():
    try:
        conn = get_connection()
        if not conn:
            raise ConnectionError("No se pudo establecer conexión con la base de datos")
        cursor = conn.cursor()
        cursor.execute("SELECT Item_preheater_volt, TechnicalSheet from CZE_ControllerPreheater")
        results = cursor.fetchall()
        if not results:  # Verifica si la tabla está vacía
            return []  # Devuelve una lista vacía si no hay datos
        return [{"Item_preheater_volt": row[0], "TechnicalSheet": row[1]} for row in results]
        
    except Exception as e:
        print(f"[Error inesperado] Error consultando breakers: {e}")
        return []
    finally:
        if conn:
            conn.close()

def update_Controlador_del_precalentador_TechnicalSheet(item, TechnicalSheet):
    """Actualiza la ficha técnica de un breaker en la base de datos."""
    query = """
    UPDATE CZE_ControllerPreheater
    SET TechnicalSheet = ?
    WHERE Item_preheater_volt = ?
    """
    try:
        conn = get_connection()
        if not conn:
            raise ConnectionError("No se pudo establecer conexión con la base de datos")
        
        cursor = conn.cursor()
        cursor.execute(query, (TechnicalSheet, item))
        conn.commit()
    except Exception as e:
        print(f"[Error inesperado] Error actualizando ficha técnica: {e}")
    finally:
        if conn:
            conn.close()