' ===================================================================
'  FRAGMENTO SIMULADO PARA EJERCICIO DE FORMACION
'  No es codigo real de ChronoSoft. Escrito con el estilo tipico de
'  VB.NET + SQL Server para que el ejercicio sea realista.
'  Reto: pedirle a la IA que lo documente, describa la funcion
'  y liste los casos borde que no estan contemplados.
' ===================================================================

Public Function TransmitirFormula(ByVal idFormula As Integer, _
                                  ByVal puerto As String, _
                                  ByVal baudios As Integer) As Integer

    Dim sp As New System.IO.Ports.SerialPort(puerto, baudios, Parity.None, 8, StopBits.One)
    Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("TMDB").ConnectionString)
    Dim total As Integer = 0

    Try
        cn.Open()
        Dim cmd As New SqlCommand("SELECT Codigo, Material, Kg, Orden FROM FormulaDetalle WHERE IdFormula = " & idFormula & " ORDER BY Orden", cn)
        Dim dr As SqlDataReader = cmd.ExecuteReader()

        sp.ReadTimeout = 3000
        sp.Open()

        While dr.Read()
            Dim trama As String = "<F" & dr("Codigo").ToString() & ";" & _
                                  dr("Material").ToString() & ";" & _
                                  dr("Kg").ToString() & ">"
            sp.Write(trama)
            Dim ack As String = sp.ReadLine()
            If ack <> "ACK" Then
                LogEvento("WARN", "ACK no recibido para " & dr("Codigo").ToString())
            Else
                total = total + 1
            End If
        End While

        dr.Close()
        sp.Close()
        cn.Close()

    Catch ex As Exception
        LogEvento("ERROR", ex.Message)
        Return -1
    End Try

    Return total

End Function
