Imports System
Imports iNTERFACEWARE.IGC

Module IGCexampleMain
    Dim WithEvents Processor As iNTERFACEWARE.IGC.MessageProcessor = New iNTERFACEWARE.IGC.MessageProcessor()
    Dim StopEvent As System.Threading.AutoResetEvent = New System.Threading.AutoResetEvent(False)
    Dim MessageSent As Boolean = False

    Sub Main(ByVal Args() As String)
        'Usage matches default executable parameters passed in by Iguana: $hostname$ $port$ $channel$ $component$
        Dim Usage As String = "Usage: IGCexample.exe Hostname Port Channel Component"

        Try
            If Args.Length <> 4 Then
                Throw New System.Exception("Invalid number of command-line arguments.")
            End If

            Dim Hostname As String = Args(0)
            Dim Port As Integer = System.Convert.ToInt16(Args(1))
            Dim Channel As String = Args(2)
            Dim Component As String = Args(3)

            If Component <> "source" Then
                Throw New System.Exception("Invalid component - only 'source' is supported by this plugin.")
            End If

            System.Console.WriteLine("Connecting to Iguana")
            Processor.connect(Hostname, Port, Channel, Component)

            ' Wait for the stop event, which is generated when the Iguana channel is stopped
            StopEvent.WaitOne()

            Return
        Catch ex As iNTERFACEWARE.IGC.Exception
            System.Console.WriteLine(ex.Description)
        Catch ex As System.Exception
            System.Console.WriteLine(ex.Message)
        End Try

        System.Console.WriteLine(Usage)
    End Sub

    ' This event is triggered when Iguana makes a request for a message.
    ' Note that the message is not considered successfully sent until Iguana generates
    ' a MessageRequestCompleted event.
    Private Sub Processor_OnMessageRequest(ByVal sender As Object, ByVal e As System.EventArgs, _
    ByVal MessageResponse As iNTERFACEWARE.IGC.MessageRequestResponse) Handles Processor.OnMessageRequest
        Dim CR As String
        CR = ControlChars.Cr
        ' Exceptions cannot be thrown out of this handler. Any exceptions thrown will abort this program.
        ' Logging and exception handling must be performed in this handler.
        Try
            ' This example simply sends a single hard-coded message.
            If (MessageSent = False) Then
                ' Load OutboundMessage with the message to be sent to Iguana.
                MessageResponse.OutboundMessage = "MSH|^~\\&|MESA_OP|XYZ_HOSPITAL|MESA_OF|XYZ_RADIOLOGY|" + _
                    "||ORM^O01|102126|P|2.3.1||||||||" + CR + _
                    "PID|||583030^^^ADT1||BROWN^JAMES||19501216|M||AI|537 PURDUE AVE^^ST. LOUIS^MO^63130" + _
                    "|||||||20-95-2000||||||||||||" + CR + _
                    "PV1||I|||||||||||||||||V1001^^^ADT1|||||||||||||||||||||||||||||||||" + CR + _
                    "ORC|CA|A102Y^MESA_ORDPLC|||||||||||||||||"
                MessageResponse.MessageId = System.DateTime.Now.ToString()
                System.Console.WriteLine("*** Message sent on " + MessageResponse.MessageId + " ***")
                System.Console.WriteLine(MessageResponse.OutboundMessage)
            Else
                ' If the message has been successfully sent, assign the empty string to OutboundMessage.
                ' This tells Iguana that there are no new messages to be sent. Iguana will keep
                ' polling this channel - and receiving this empty string - until the channel is stopped.
                MessageResponse.OutboundMessage = ""
            End If

            ' If the plugin detects an error when trying to create a message, set OutboundMessage
            ' to contain a description of the error, and set MessageIsError to true.
            '
            '    MessageResponse.OutboundMessage = "Error detected when trying to send message"
            '    MessageResponse.MessageIsError = True

            ' You can use StopChannel, StopChannelErrorFlag, and StopChannelReason to stop the Iguana 
            ' channel with or without an error flag, and provide a reason for the stop request.
            '
            '    MessageResponse.StopChannel = True
            '    MessageResponse.StopChannelErrorFlag = True
            '    MessageResponse.StopChannelReason = "An error occurred."

            ' You can send additional error/info/debug log messages to Iguana with addLogMessage().
            '
            '    MessageResponse.addLogMessage(IGClogMessageType.Error, "Error log message")
            '    MessageResponse.addLogMessage(IGClogMessageType.Info, "Info log message")
            '    MessageResponse.addLogMessage(IGClogMessageType.Debug, "Debug log message")
            '    MessageResponse.addLogMessage(IGClogMessageType.Warning, "Warning log message")

            ' You can use addLogValue() to send additional Key/Value pair logging information to Iguana.
            '
            '    MessageResponse.AddLogValue("MyField", "Message successfully processed.")
        Catch ex As iNTERFACEWARE.IGC.Exception
            System.Console.WriteLine(ex.Description)
        Catch ex As System.Exception
            System.Console.WriteLine(ex.Message)
        End Try
    End Sub

    ' This message is triggered when Iguana has completed processing a message that was sent by
    ' OnMessageRequest.
    ' If this event is not received, the message sent by the MessageRequest event handler was
    ' not processed successfully. This means that the message may need to be resent.
    Private Sub Processor_OnMessageRequestCompleted(ByVal sender As Object, ByVal e As System.EventArgs, _
     ByVal MessageID As String, ByVal Succeeded As Boolean) Handles Processor.OnMessageRequestCompleted
        ' Exceptions cannot be thrown out of this handler. Any exceptions thrown will abort this program.
        ' Logging and exception handling must be performed in this handler.
        Try
            System.Console.WriteLine("*** Message sent successfully ***")
            MessageSent = True
        Catch ex As iNTERFACEWARE.IGC.Exception
            System.Console.WriteLine(ex.Description)
        Catch ex As System.Exception
            System.Console.WriteLine(ex.Message)
        End Try
    End Sub

    ' This event is triggered when the Iguana channel is shut down.
    Private Sub Processor_OnDisconnect(ByVal sender As Object, ByVal e As System.EventArgs, _
        ByVal ReasonFlags As MessageProcessor.IGCdisconnectReasonFlags, ByVal ReasonDescription As String) _
        Handles Processor.OnDisconnect
        ' Exceptions cannot be thrown out of this handler. Any exceptions thrown will abort this program.
        ' Logging and exception handling must be performed in this handler.
        Try
            If (MessageProcessor.isDisconnectByError(ReasonFlags)) Then
                System.Console.WriteLine("Connection closed by error: " + ReasonDescription)
            ElseIf (MessageProcessor.isDisconnectByPlugin(ReasonFlags)) Then
                System.Console.WriteLine("Plugin closed the connection")
            ElseIf (MessageProcessor.isDisconnectByIguana(ReasonFlags)) Then
                System.Console.WriteLine("Iguana closed the connection")
            Else
                System.Console.WriteLine("Connection closed: " + ReasonDescription)
            End If
            StopEvent.Set()
        Catch ex As iNTERFACEWARE.IGC.Exception
            System.Console.WriteLine(ex.Description)
        Catch ex As System.Exception
            System.Console.WriteLine(ex.Message)
        End Try
    End Sub

End Module
