using System;
using System.Net;
using System.Web.Services.Protocols;
using RadiologyResultSampleCodeCS.RadiologyResultsWebService;

namespace RadiologyResultSampleCodeCS
{
    class RadiologyResultSample
    {
        /**
         * Replace "test" and "customer1" with the username and password MedPlus has
         * assigned to you.
         * 
         * 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 const string USERNAME = "test";
        private const string PASSWORD = "customer1";

        // WEB_SERVICE_URL designates the end point used to
        // connect to the Hub's Results web service
        private const string WEB_SERVICE_URL = "https://cert.hub.care360.com/radiology/result/service";

        // SENDING_APPLICATION designates the application that is sending the radiology result
        // message to Hub
        private const String SENDING_APPLICATION = "HUBWS";

        // SENDING_FACILITY designates the service provider name assigned to you by MedPlus.
        private const String SENDING_FACILITY = "2135800";

        // RECEIVING_FACILITY designates a provider account name that will be receiving the result.
        // Provider accounts will be determined and provided by MedPlus as part of interface development.
        private const String RECEIVING_FACILITY = "THO";

        /*
         * The HL7 radiology result message template - The following "template" is used in
         * constructing the radiology result.
         * 
         * 0 = sending application (field 3) 
         * 1 = sending facility (field 4) represents the account with Quest Diagnostics 
         * 2 = receiving facility (field 6) The Quest Business Unit for above account 
         * 3 = date time (field 7) 
         * 4 = message control id (field 10) Unique Number identifying this radiology result message
         * 
         */
        private const String RADIOLOGY_RESULT_MESSAGE = "MSH|^~\\&|{0}|{1}||{2}|{3:yyyyMMddHHmm}||ORU^R01|{4}|P|2.3\r"
	        + "PID|||123456789^^^F|123456789|TEST^WIFE||19560101|F|||||(206)783-4||*ENGLISH^E|S||9918210003|123456789\r"
	        + "OBR||{4}|{4}|30070^MR CHEST W/O CONTRAST^RAD||20100514095201|20100514095201|20100514095201||||||||OTH030^DOCTOR^A^^^^^UPIN||||||20100514095201|||F|||||||999999&Transcriptionist&The&A|999999&Transcriptionist&The&A||999999&<None>\r"
            + "OBX|1|FT|RAD|| ||||||F|||||999999\r"
            + "OBX|2|FT|RAD||The findings: Frontal view of the chest compared to earlier studies of||||||F|||||999999\r"
            + "OBX|3|FT|RAD||12/11/2003 and 12/31/2003.||||||F|||||999999\r"
            + "OBX|4|FT|RAD|| ||||||F|||||999999\r"
            + "OBX|5|FT|RAD||Again, the study was obtained and a poor degree of inspiration. There||||||F|||||999999\r"
            + "OBX|6|FT|RAD||is a mild prominence of the interstitial markings particularly at the||||||F|||||999999\r"
            + "OBX|7|FT|RAD||bases and these could easily represent atelectasis. The cardiac||||||F|||||999999\r"
            + "OBX|8|FT|RAD||silhouette is borderline normal. Hilar and mediastinal silhouettes are||||||F|||||999999\r"
            + "OBX|9|FT|RAD||normal for this degree of inspiration. There is no effusion or||||||F|||||999999\r"
            + "OBX|10|FT|RAD||pneumothorax.||||||F|||||999999\r"
            + "OBX|11|FT|RAD|| ||||||F|||||999999\r"
            + "OBX|12|FT|RAD||Impression:||||||F|||||999999\r"
            + "OBX|13|FT|RAD|| ||||||F|||||999999\r"
            + "OBX|14|FT|RAD||Poor inspiration with compression of pulmonary markings. No definite||||||F|||||999999\r"
            + "OBX|15|FT|RAD||acute process is identified||||||F|||||999999\r";

        public RadiologyResultSample()
        {
            RadiologyResultService webService = null;

            try
            {
                //-------------------------------------------------------
                //STEP 1: CREATE WEB SERVICE REFERENCE
                //-------------------------------------------------------
                webService = new RadiologyResultService();
            }
            catch (Exception ex)
            {
                Console.Write(ex.StackTrace);
                webService = null;
            }

            if (!(webService == null))
            {
                RadiologyResultResponse response = null;
                RadiologyResult result = null;

                try
                {
                    //------------------------------------------------------------------
                    //STEP 2: CREATE CREDENTIALS OBJECT CONTAINING USERNAME AND PASSWORD
                    //------------------------------------------------------------------
                    webService.Credentials = new NetworkCredential(USERNAME, PASSWORD);

                    // By default the client will attempt to call the web service without 
                    // sending the credentials. If the server returns a 401 HTTP response, 
                    // the client makes the call again with the credentials. If we set 
                    // PreAuthenticate to True, the client will include the credentials on 
                    // the initial call and eliminate this extra processing.
                    //
                    // This should probably be set in the web service object's constructor,
                    // but has been included here to demonstrate.
                    webService.PreAuthenticate = true;


                    //------------------------------------------------------------------
                    //STEP 3: SET WEB SERVICE URL
                    //------------------------------------------------------------------
                    if (WEB_SERVICE_URL.Length > 0)
                    {
                        webService.Url = WEB_SERVICE_URL;
                    }

                    //------------------------------------------------------------------
                    //STEP 4: GENERATE RESULT OBJECT
                    //------------------------------------------------------------------
                    result = getWebServiceRadiologyResult();

                    //--------------------------------------------------------------
                    //STEP 5: SUBMIT RESULT TO THE HUB
                    //--------------------------------------------------------------

                    response = webService.submitRadiologyResult(result);
                    
                }
                catch (SoapException soapEx)
                {
                    string exceptionMessage = soapEx.Detail.InnerText.Replace("" +
                        (char)10 + "", "" + (char)13 + "" +
                        (char)10 + "");

                    Console.Write(exceptionMessage);
                }

                if (!(response == null))
                {
                    //------------------------------------------------
                    //STEP 7: EXAMINE RESPONSE FROM THE HUB
                    //------------------------------------------------
                    Console.WriteLine("Status: <{0}>.", response.status);
                    Console.WriteLine("Message Control Id: <{0}>.", response.messageControlId);
                    Console.WriteLine("Response Message: <{0}>.", response.responseMsg);

                    if (!(response.validationErrors == null))
                    {
                        foreach (string valErr in response.validationErrors)
                        {
                            Console.WriteLine("Validation Error: <{0}>.", valErr);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Failed to properly call submitOrder WebService method.");
                }
            }
        }

        private RadiologyResult getWebServiceRadiologyResult()
        {
            RadiologyResult result = new RadiologyResult();
            String resultMessage;
            Byte[] resultByteArray;

            // Create Order Mesage by passing in facility information
            resultMessage = buildRadiologyResultMessage(SENDING_APPLICATION, SENDING_FACILITY, RECEIVING_FACILITY);
            // Convert String to a Byte array and return in an Order object
            resultByteArray = System.Text.Encoding.ASCII.GetBytes(resultMessage);
            result.hl7RadiologyResult = resultByteArray;

            return result;
        }

        private string buildRadiologyResultMessage(string SENDING_APPLICATION, string SENDING_FACILITY, string RECEIVING_FACILITY)
        {
            //'now' is used for 2 purposes here
            //1 to specify the time that the message was created
            //2 to create a unique message control ID and order number
            System.DateTime now = System.DateTime.Now;
            // parameters for replacement in the template
            Object[] msgParams = new Object[7];
            msgParams[0] = SENDING_APPLICATION;
            msgParams[1] = SENDING_FACILITY;
            msgParams[2] = RECEIVING_FACILITY;
            msgParams[3] = now;
            msgParams[4] = now.Ticks;
            return string.Format(RADIOLOGY_RESULT_MESSAGE, msgParams);
        }
    }
}
