Imports System
Imports System.IO
Imports System.Net
Imports System.Web.Services.Protocols
Imports System.Text

Public Class RetrieveResultsRestSample


    ' Constants that define the three result service types.
    Private Const RESULT_SERVICE_TYPE_HL7 As String = "HL7"
    Private Const RESULT_SERVICE_TYPE_PRINTABLE As String = "Printable"
    Private Const RESULT_SERVICE_TYPE_OBSERVATION As String = "Observation"

    ' Constants that define request parameter names.
    Private Const REQUEST_PARAMETER_NAME_MAX_MESSAGES As String = "maxMessages"
    Private Const REQUEST_PARAMETER_NAME_MESSAGE_CONTROL_ID As String = "messageControlId"
    Private Const REQUEST_PARAMETER_NAME_PROVIDER_ACCT_ID As String = "providerAcctId"

    ' The HL7/Observation ACK message template - The following "template" is
    ' used in constructing an ACK request message. After calling getResults()
    ' for HL7 or Observation results, you will acknowledge receipt of the
    ' results by calling acknowledgeResults(). The acknowledgeResults() request
    ' contains an acknowledge message constructed from the HL7 message
    ' retrieved.
    ' 
    ' 0 = sending application (field MSH.03) 
    ' 1 = sending facility (field MSH.04) 
    ' 2 = receiving application (field MSH.05) 
    ' 3 = receiving facility (field MSH.06) 
    ' 4 = date time (field MSH.07) 
    ' 5 = message control id (field MSH.10) 
    ' 6 = hl7 version (field MSH.12)
    ' 7 = message control id of message (field MSA.02)
    Const ACK_MESSAGE_FORMAT As String = _
         "MSH|^~\&|{0}|{1}|{2}|{3}|{4:yyyyMMddHHmm}||ACK|{5:#####}|D|{6}" + vbCr + _
         "MSA|CA|{7}" + vbCr

    ' USERNAME designates the Hub user name used to
    ' authenticate to the Hub web service
    Private Const USERNAME As String = "DYNAMIC_TEST"

    ' PASSWORD designates the password associated with
    ' the Hub user when authenticating to the web service
    Private Const PASSWORD As String = "passw0rd"

    ' WEB_SERVICE_URL designates the end point used to
    ' connect to the Hub's Printbale Results web service
    Private Const URL_GET_RESULTS As String = "http://localhost:7001/rest/results/v1/retrieval/getResults/"
    Private Const URL_ACK_RESULTS As String = "http://localhost:7001/rest/results/v1/retrieval/acknowledgeResults/"

    ' Maximum number of messages to retrieve
    Private Const MAX_MESSAGES As String = "5"

    ' can be "observation", "printable", or "hl7".  The constants defined above can be used for this
    Private resultServiceType As String = RESULT_SERVICE_TYPE_HL7

    ' HL7 uses carriage return only = ASCII 13
    Private Const CR As Char = Chr(13)
    Private Const LF As Char = Chr(10)


    Public Sub run()
        Try
            Console.WriteLine("Calling getResultsViaRest...")
            Dim REST_WEB_SERVICE_URI As Uri = New Uri(URL_GET_RESULTS)
            getResultsViaRest(REST_WEB_SERVICE_URI)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub

    ' The submitOrderViaRest function handles the interactions with the Hub’s REST interface
    Public Sub getResultsViaRest(ByVal target As Uri)

        Dim response As HttpWebResponse = Nothing
        Dim postStream As Stream = Nothing

        '------------------------------------------------------------------------
        'STEP 1: CONFIGURE CONNECTION TO REST ENDPOINT WITH BASIC AUTHENTICATION
        '------------------------------------------------------------------------
        Dim request As WebRequest = WebRequest.Create(URL_GET_RESULTS)
        request.Method = "POST"
        request.ContentType = "application/json"
        request.Credentials = New NetworkCredential(USERNAME, PASSWORD)

        '----------------------------------------------------
        'STEP 2: FORMAT THE REQUEST MESSAGE FOR getResults
        '----------------------------------------------------
        submitViaRest(buildJSONRequestBody(), request)

        '----------------------------------------------------
        'STEP 3: SUBMIT THE REQUEST TO THE HUB REST SERVICE FOR getResults
        '----------------------------------------------------
        response = DirectCast(request.GetResponse(), HttpWebResponse)

        Dim reader As StreamReader = New StreamReader(response.GetResponseStream())
        Console.Write(reader.ReadToEnd())

        '------------------------------------------------------------------------
        'STEP 4: CONFIGURE THE REST ENDPOINT FOR ACKNOWLEDGE RESULTS
        '------------------------------------------------------------------------
        Dim requestAck As WebRequest = WebRequest.Create(URL_ACK_RESULTS)
        requestAck.Credentials = New NetworkCredential(USERNAME, PASSWORD)
        requestAck.Method = "POST"
        requestAck.ContentType = "application/json"

        '----------------------------------------------------
        'STEP 5: FORMAT THE REQUEST MESSAGE FOR acknowledgeResults
        '----------------------------------------------------
        'submitViaRest(buildAckJSONRequestBody(), request)

        '----------------------------------------------------
        'STEP 6: SUBMIT THE REQUEST TO THE HUB REST SERVICE FOR acknowledgeResults
        '----------------------------------------------------
        'Dim responseAck As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
        'Dim readerAck As StreamReader = New StreamReader(responseAck.GetResponseStream())
        'Console.Write(readerAck.ReadToEnd())


    End Sub


    Private Function buildJSONRequestBody() As Byte()

        Dim json As String

        json = "{""resultServiceType"":""hl7"","
        json += """providerAccounts"":[{""providerAccountName"":""DYNAMIC_TEST"",""providerName"":""DYNAMIC_TEST""}],"
        json += """requestParameters"":[{""parameterName"":""maxMessages"",""parameterValue"":""1""}]}"

        Return System.Text.Encoding.Default.GetBytes(json)

    End Function

    Private Function buildAckJSONRequestBody() As Byte()

        Dim json As String

        Dim requestId As String = ""   'Request Id
        Dim strMessage As String = ""  'Base64 encoded Ack message
        Dim controlId As String = ""   'Control Id

        json = "{""resultServiceType"":""hl7"",""requestId"":"""
        json += requestId
        json += """,""ackMessages"":[,""ackMessages"":[{""message"":"""
        json += strMessage
        json += """,""controlId"":"""
        json += controlId
        json += """}]}"

        Return System.Text.Encoding.Default.GetBytes(json)


    End Function


    Private Sub submitViaRest(ByVal encodedMessage As Byte(), ByVal request As WebRequest)
        Dim messageLength As Integer = encodedMessage.Length
        request.ContentLength = messageLength
        Dim dataStream As Stream = request.GetRequestStream()
        Try
            dataStream.Write(encodedMessage, 0, messageLength)
        Finally
            dataStream.Close()
        End Try
    End Sub



End Class

