package hub.sample;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;

import javax.xml.bind.DatatypeConverter;

public class RetrieveResultsRestClient {

    /**
     * You will pass the username and password when you get the stub later in
     * this example. Via the stub, you'll make the method calls to the Results
     * Web Service to retrieve lab results.
     */
    //private static final String DOCUMENT_ENDPOINT = "https://cert.hub.care360.com/rest/orders/v1/document";
    //private static final String USERNAME = "test";
    //private static final String PASSWORD = "customer1";

    private static final String DOCUMENT_ENDPOINT = "http://localhost:7001/rest/results/v1/retrieval/getResults/";
    private static final String ACK_ENDPOINT = "http://localhost:7001/rest/results/v1/retrieval/acknowledgeResults/";
    private static final String USERNAME = "DYNAMIC_TEST";
    private static final String PASSWORD = "passw0rd";

    
    
    //private static final String DOCUMENT_ENDPOINT = "https://cert.hub.care360.com/rest/orders/v1/document";
    //private static final String USERNAME = "test";
    //private static final String PASSWORD = "customer1";

    // SENDING_APPLICATION designates the application that is sending the order
    // message to Hub
    private static final String SENDING_APPLICATION = "HUBWS";

    // SENDING_FACILITY designates the account number provided to you by Quest
    // for the business unit you are ordering tests with
    private static final String SENDING_FACILITY = "97502840";

    // RECEIVING_FACILITY designates the business unit within Quest from which
    // the labs are being ordered
    private static final String RECEIVING_FACILITY = "NEL";

    public static void main(String[] args) throws Exception {
        // Retrieve the HL7 Results via REST
        requestGetResults();
    }

    private static void requestGetResults() throws Exception {
        HttpURLConnection conn = null;
        try {
            // -------------------------------------------------
            // STEP 1: CONFIGURE CONNECTION TO REST ENDPOINT
            // -------------------------------------------------
            conn = (HttpURLConnection) (new URL(DOCUMENT_ENDPOINT).openConnection());
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            String credentials = USERNAME + ":" + PASSWORD;
            String encodedCredentials = DatatypeConverter.printBase64Binary(credentials.getBytes());
            conn.setRequestProperty("Authorization", "Basic " + encodedCredentials);

            // ------------------------------------------------------------------
            // STEP 2: WRITE MESSAGE TO THE OPEN CONNECTION
            // ------------------------------------------------------------------
            String request = "";

        	request = "{\"resultServiceType\":\"hl7\",";
            request += "\"providerAccounts\":[{\"providerAccountName\":\"DYNAMIC_TEST\",\"providerName\":\"DYNAMIC_TEST\"}],";
            request += "\"requestParameters\":[{\"parameterName\":\"maxMessages\",\"parameterValue\":\"1\"}]}";
            
            OutputStream os = conn.getOutputStream();
            os.write(request.getBytes());
            os.flush();

            // -------------------------------------------------
            // STEP 3: EXAMINE RESPONSE COMING BACK FROM THE HUB
            // -------------------------------------------------
            StringBuilder serverResponse = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String line;
            while ((line = br.readLine()) != null) {
                serverResponse.append(line);
            }

            System.out.println("Response Message:");
            System.out.println(serverResponse.toString());
            
            
            // -------------------------------------------------
            // STEP 4: CONFIGURE CONNECTION TO REST ENDPOINT FOR ACKNOWLEDGEMENT
            // -------------------------------------------------
            conn = (HttpURLConnection) (new URL(ACK_ENDPOINT).openConnection());
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            credentials = USERNAME + ":" + PASSWORD;
            encodedCredentials = DatatypeConverter.printBase64Binary(credentials.getBytes());
            conn.setRequestProperty("Authorization", "Basic " + encodedCredentials);

            // ------------------------------------------------------------------
            // STEP 5: WRITE MESSAGE TO THE OPEN CONNECTION
            // ------------------------------------------------------------------
            String ackRequest = "";
            String requestId = "";   //Request Id for the transaction
            String strMessage = "";  //Base64 Encoded HL7 Ack Message
            String controlId = "";   //Control Id 
             
            ackRequest = "{\"resultServiceType\":\"hl7\",";
            ackRequest += "\"requestId\":\"";
      		ackRequest += requestId;
      		ackRequest += "\",\"ackMessages\":[{\"message\":\"";
            ackRequest += strMessage;
            ackRequest += "\",\"controlId\":\"";
            ackRequest += controlId;
            ackRequest += "\"}]}";

            System.out.println("\nAck Request:");
            System.out.println(ackRequest);

            OutputStream osAck = conn.getOutputStream();
            osAck.write(ackRequest.getBytes());
            osAck.flush();

            // -------------------------------------------------
            // STEP 6: EXAMINE RESPONSE COMING BACK FROM THE HUB
            // -------------------------------------------------
            StringBuilder serverAckResponse = new StringBuilder();
            BufferedReader brAck = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String ackLine;
            while ((ackLine = brAck.readLine()) != null) {
                serverAckResponse.append(ackLine);
            }

            System.out.println("\nResponse Message:");
            System.out.println(serverAckResponse.toString());
            
        } finally {
            conn.disconnect();
        }
    }

    
    
}
