using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;


namespace RetrieveResultsRestSampleCodeCS
{
    /// <summary>
    /// Class OrderRestSample submits lab order (HL7 messages) to the MedPlus
    /// Hub platform via REST web service.
    /// </summary>
    class RetrieveResultsRestSample
    {
        // USERNAME designates the Hub user name used to
        // authenticate to the Hub web service
        private const string USERNAME = "DYNAMIC_TEST";

        // PASSWORD designates the password associated with
        // the Hub user when authenticating to the web service
        private const string PASSWORD = "passw0rd";   // default password

        //WEB_SERVICE_URL designates the end point used to getResults and acknowledgeResults
        private const string URL_GET_RESULTS = "http://localhost:7001/rest/results/v1/retrieval/getResults/";
        private const string URL_ACK_RESULTS = "http://localhost:7001/rest/results/v1/retrieval/acknowledgeResults/";

        private const char CR = (char)13;
        private const char LF = (char)10;
        private string NEWLINE = string.Format("{0}{1}", CR, LF);
        private string HL7_LINEBREAK = string.Format("{0}", CR);

        /// <summary>
        /// Retrieve Results via REST web service interface. Supply REST web service
        /// endpoint url as string argument.
        /// </summary>
        public void retrieveResultsViaRest()
        {
            HttpWebResponse response = null;
            Stream postStream = null;

            //------------------------------------------------------------------------
            //STEP 1: CONFIGURE CONNECTION TO REST ENDPOINT WITH BASIC AUTHENTICATION
            //------------------------------------------------------------------------
            HttpWebRequest request = getWebRequest(new Uri(URL_GET_RESULTS));
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Credentials = new NetworkCredential(USERNAME, PASSWORD);

            //----------------------------------------------------
            //STEP 2: FORMAT THE REQUEST MESSAGE FOR getResults
            //----------------------------------------------------
            string requestBody;

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

            Console.Write("\nRequest getResults :\n");
            Console.Write(requestBody);
         
            
            //----------------------------------------------------
            //STEP 3: SUBMIT THE REQUEST TO THE HUB REST SERVICE
            //----------------------------------------------------
            try
            {
                postStream = request.GetRequestStream();
                postStream.Write(UTF8Encoding.UTF8.GetBytes(requestBody), 0, requestBody.Length);
            }
            finally
            {
                if (postStream != null) postStream.Close();
            }

            //---------------------------------------------------------------
            //STEP 4: READ RESPONSE FROM THE HUB, DECODE AND ECHO TO CONSOLE
            //---------------------------------------------------------------
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string lines = reader.ReadToEnd();
                Console.Write("\n\nResponse getResults :\n");
                Console.Write(lines);
            }
            finally
            {
                if (response != null) response.Close();
            }
        }

        /// <summary>
        /// Returns an HttpWebRequest object to use to communicate with the REST web
        /// service. Broken out here just because it can throw an exception which has
        /// the potential to halt the run.
        /// </summary>
        private HttpWebRequest getWebRequest(Uri target)
        {
            HttpWebRequest result = null;
            try
            {
                result = (HttpWebRequest)WebRequest.Create(target);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Environment.Exit(0);
            }
            return result;
        }

    }
}
