package net.ihe.xcpd.init.action;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import net.ihe.gazelle.simulator.common.model.ApplicationConfiguration;
import net.ihe.xcpd.init.assertion.AssertionGenerator;
import net.ihe.xcpd.init.model.Assertion;
import net.ihe.xcpd.init.transport.Client2Server;
import net.ihe.xcpd.init.transport.SOAPSender2;

import org.w3c.dom.Element;

/**
 * @author abderrazek boufahja
 */
public class HL7V3Responder {

    public static String generateResponse(String requestV3, String wsURL, boolean isXUA) throws Exception{
        if (wsURL == null) return null;
        if (wsURL.equals("")) return null;
        String requestSOAP = generateRequestSOAP(requestV3, isXUA, wsURL);
        String res = SOAPSender2.sendToUrlAndGetResponse(wsURL, requestSOAP);
        return res;
        /*
        if (!isXUA){
            if (requestV3 != null && wsURL != null){
                if ((!requestV3.equals(""))&&(!wsURL.equals(""))){
                    Client2Server c2s = new Client2Server();
                    responseV3 = c2s.getSOAPResponse(null, requestV3, wsURL);
                    //XUser xu = new XUser();
                    //Element e = xu.getServerResponse(null, requestV3, wsURL);
                    //responseV3 = formatDocument(e);
                    responseV3 = XmlFormatter.prettyFormat(responseV3,3);
                }
            }
        }
        else{
            if (requestV3 != null && wsURL != null){
                if ((!requestV3.equals(""))&&(!wsURL.equals(""))){
                    String STSurl = ApplicationConfiguration.getValueOfVariable("sts_url");
                    String serviceName = ApplicationConfiguration.getValueOfVariable("sts_service_name");
                    String port = ApplicationConfiguration.getValueOfVariable("sts_port");
                    String asser = AssertionGenerator.generateToken(STSurl, serviceName, port);
                    Assertion.mergeAssertion(new Assertion(asser, STSurl, serviceName, port, new Date()));
                    System.out.println("HL7V3Gen.asser = " + asser);
                    System.out.println("HL7V3Gen.requestV3 = " + requestV3);
                    Client2Server c2s = new Client2Server();
                    responseV3 = c2s.getSOAPResponse(asser, requestV3, wsURL);
                    //XUser xu = new XUser();
                    //Element e = xu.getServerResponse(asser, requestV3, wsURL);
                    if (responseV3 != null){
                        responseV3 = XmlFormatter.prettyFormat(responseV3,3);
                    }
                }
            }
        }
                return responseV3;

        //*/
    }
    
    public static String generateRequestSOAP(String requestV3, boolean isXUA, String endPoint) throws Exception{
        String requestSOAP = new String();
        Client2Server c2s = new Client2Server();
        if (!isXUA){
            if (requestV3 != null){
                if (!requestV3.equals("")){
                    requestSOAP = c2s.createMessageSoap(null, requestV3, endPoint);
                }
            }
        }
        else{
            if (requestV3 != null){
                if (!requestV3.equals("")){
                    String STSurl = ApplicationConfiguration.getValueOfVariable("sts_url");
                    String serviceName = ApplicationConfiguration.getValueOfVariable("sts_service_name");
                    String port = ApplicationConfiguration.getValueOfVariable("sts_port");
                    String nameID = ApplicationConfiguration.getValueOfVariable("nameID");
                    String patientID = ApplicationConfiguration.getValueOfVariable("patientID");
                    String asser = AssertionGenerator.generateToken(nameID,patientID);
                    Assertion.mergeAssertion(new Assertion(asser, new Date()));
                    System.out.println("HL7V3Gen.asser = " + asser);
                    System.out.println("HL7V3Gen.requestV3 = " + requestV3);
                    requestSOAP = c2s.createMessageSoap(asser, requestV3, endPoint);
                }
            }
        }
        return requestSOAP;
    }


    public static String formatDocument(Element document) throws IOException, TransformerException
    {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        StringWriter sw = new StringWriter();
        trans.transform(new DOMSource(document), new StreamResult(sw));
        String theAnswer = sw.toString();
        return theAnswer;
    }
    
    public static void main(String[] args) {
        String init = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:urn=\"urn:hl7-org:v3\">" +
		"<soap:Header><ns3:Assertion xmlns:ns3=\"urn:oasis:names:tc:SAML:2.0:assertion\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns=\"http://www.w3.org/2001/04/xmlenc#\" xmlns:ns4=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\" xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns5=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:ns6=\"http://www.w3.org/2000/09/xmldsig#\" ID=\"ID_228e5344-91dd-4ee9-8f40-ac376a2b9d83\" IssueInstant=\"2010-10-13T12:40:22.928Z\" Version=\"2.0\"><ns3:Issuer>urn:idp:demo</ns3:Issuer><dsig:Signature xmlns:dsig=\"http://www.w3.org/2000/09/xmldsig#\"><dsig:SignedInfo><dsig:CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/><dsig:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/><dsig:Reference URI=\"#ID_228e5344-91dd-4ee9-8f40-ac376a2b9d83\"><dsig:Transforms><dsig:Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/><dsig:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/></dsig:Transforms><dsig:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/><dsig:DigestValue>zL9zR7P4yfNYaJs/WqLmx+EefCE=</dsig:DigestValue></dsig:Reference></dsig:SignedInfo><dsig:SignatureValue>muDYOLU3Qu/GHRgwmTzWW85m05ch2UwrvUHY458fAhMIZx/uqX5RtZg0jGVSdemLfv0pvyh79yTycMKK9+1lsCDGO+uFuh4eM92CvaprwLEHx51beignvgmTh0meKdwv9RgNqUr3Vvu/OB1o2Lj2jPo0tTvkX4DAs1aU2dcmeXc=</dsig:SignatureValue><dsig:KeyInfo><dsig:X509Data><dsig:X509Certificate>MIICUDCCAbkCBEn1/6gwDQYJKoZIhvcNAQEEBQAwbzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMRAwDgYDVQQHEwdSYWxlaWdoMRQwEgYDVQQKEwtSZWQgSGF0IEluYzEXMBUGA1UECxMOSkJvc3MgRGl2aXNpb24xEjAQBgNVBAMTCUpCb3NzIFNUUzAeFw0wOTA0MjcxODU1MzZaFw0wOTA3MjYxODU1MzZaMG8xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJOQzEQMA4GA1UEBxMHUmFsZWlnaDEUMBIGA1UEChMLUmVkIEhhdCBJbmMxFzAVBgNVBAsTDkpCb3NzIERpdmlzaW9uMRIwEAYDVQQDEwlKQm9zcyBTVFMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALLhiMoVU2xbw8GXcfAL+ts5j/mhjpbATfFlBN3hBHA7TiGYDu/EiJjEBsAdgtHiFTIYi0c1T6qFtXQjwL3k5uud8xzprm2qbNX2NJSyQ0mW024Y3mIaEJpmga6P7Q6VcOZSiZ7NqlZzLkStfY7tncaSsJWBhraz+VUL9NHXzT27AgMBAAEwDQYJKoZIhvcNAQEEBQADgYEArEeh+zEX7ibbf9qgDqOHyKV+7bnTy4IrWL5sbdOVWTuVoOYmxL5/bWqaWvNxnglKeWX+Nb9EOqEw1eyiNiDcFbBd/liIefq6yZTzdUhqDRitpFy/OyuF6p5NX4jRvyiPh4ifAn5SLGqfUNvi1m1K/JhVtG6leFZYvIYDv833coE=</dsig:X509Certificate></dsig:X509Data></dsig:KeyInfo></dsig:Signature><ns3:Subject><ns3:NameID Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" NameQualifier=\"urn:picketlink:identity-federation\">ihelocal</ns3:NameID><ns3:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\"/></ns3:Subject><ns3:Conditions NotBefore=\"2010-10-13T12:40:22.928Z\" NotOnOrAfter=\"2010-10-13T14:40:22.928Z\"/><ns3:AuthnStatement AuthnInstant=\"2010-10-13T12:40:22.928Z\" SessionNotOnOrAfter=\"2010-10-13T14:40:22.928Z\"><ns3:AuthnContext><ns3:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:X509</ns3:AuthnContextClassRef></ns3:AuthnContext></ns3:AuthnStatement><ns3:AttributeStatement/></ns3:Assertion></soap:Header>" +
		"<soap:Body>" +
		"<PRPA_IN201305UV02 ITSVersion=\"XML_1.0\" xmlns=\"urn:hl7-org:v3\">" +
        "<id extension=\"1263507841148\" root=\"2306fc92-7819-419b-a6a6-f30d7fbeb08f\"/>" +
        "<creationTime value=\"20100114162401.148-0600\"/>" +
        "<versionCode code=\"V3PR1\"/>" +
        "<interactionId extension=\"PRPA_IN201305UV02\" root=\"2.16.840.1.113883.1.6\"/>" +
        "<processingCode code=\"P\"/>" +
        "<processingModeCode code=\"T\"/>" +
        "<acceptAckCode code=\"AL\"/>" +
        "<receiver typeCode=\"RCV\">" +
        "<device classCode=\"DEV\" determinerCode=\"INSTANCE\">" +
        "<id root=\"1.3.6.1.4.1.21367.2010.1.3.2.750\"/>" +
        "<asAgent classCode=\"AGNT\">" +
        "<representedOrganization classCode=\"ORG\" determinerCode=\"INSTANCE\">" +
        "<id root=\"1.3.6.1.4.1.21367.2010.1.3.2.750\"/>" +
        "</representedOrganization>" +
        "</asAgent>" +
        "</device>" +
        "</receiver>" +
        "<sender typeCode=\"SND\">" +
        "<device classCode=\"DEV\" determinerCode=\"INSTANCE\">" +
        "<id root=\"1.3.6.1.4.1.21367.2010.1.3.2.705\"/>" +
        "<asAgent classCode=\"AGNT\">" +
        "<representedOrganization classCode=\"ORG\" determinerCode=\"INSTANCE\">" +
        "<id root=\"1.3.6.1.4.1.21367.2009.2.2.100\"/>" +
        "</representedOrganization>" +
        "</asAgent>" +
        "</device>" +
        "</sender>" +
        "<controlActProcess classCode=\"CACT\" moodCode=\"EVN\">" +
        "<code code=\"PRPA_TE201305UV02\" codeSystemName=\"2.16.840.1.113883.1.6\"/>" +
        "<authorOrPerformer typeCode=\"AUT\">" +
        "<assignedPerson classCode=\"ASSIGNED\"/>" +
        "</authorOrPerformer>" +
        "<queryByParameter>" +
        "<queryId root=\"1263507841149\"/>" +
        "<statusCode code=\"new\"/>" +
        "<responseModalityCode code=\"R\"/>" +
        "<responsePriorityCode code=\"I\"/>" +
        "<matchCriterionList/>" +
        "<parameterList>" +
        "<livingSubjectName>" +
        "<value>" +
        "<family>A*</family>" +
        "</value>" +
        "<semanticsText>LivingSubject.name</semanticsText>" +
        "</livingSubjectName>" +
        "</parameterList>" +
        "</queryByParameter>" +
        "</controlActProcess>" +
        "</PRPA_IN201305UV02>" +
        "</soap:Body>" +
        "</soap:Envelope>";
        
        
        String rr = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:urn=\"urn:hl7-org:v3\">" +
        		"<soap:Header></soap:Header>" +
        		"<soap:Body>" +
        		"<PRPA_IN201305UV02 xmlns=\"urn:hl7-org:v3\" ITSVersion=\"XML_1.0\">" +
        		"<id extension=\"1263507841148\" root=\"2306fc92-7819-419b-a6a6-f30d7fbeb08f\"/>" +
        		"<creationTime value=\"20101012160139\"/>" +
        		"<versionCode code=\"V3PR1\"/>" +
        		"<interactionId extension=\"PRPA_IN201305UV02\" root=\"2.16.840.1.113883.1.6\"/>" +
        		"<processingCode code=\"P\"/>" +
        		"<processingModeCode code=\"T\"/>" +
        		"<acceptAckCode code=\"AL\"/>" +
        		"<receiver typeCode=\"RCV\">" +
        		"<device classCode=\"DEV\" determinerCode=\"INSTANCE\">" +
        		"<id root=\"1.1.2\"/>" +
        		"<asAgent classCode=\"AGNT\">" +
        		"<representedOrganization classCode=\"ORG\" determinerCode=\"INSTANCE\">" +
        		"<id root=\"1.1.2\"/>" +
        		"</representedOrganization>" +
        		"</asAgent>" +
        		"</device>" +
        		"</receiver>" +
        		"<sender typeCode=\"SND\">" +
        		"<device classCode=\"DEV\" determinerCode=\"INSTANCE\">" +
        		"<id root=\"1.1.1\"/>" +
        		"<asAgent classCode=\"AGNT\">" +
        		"<representedOrganization classCode=\"ORG\" determinerCode=\"INSTANCE\">" +
        		"<id root=\"1.1.1\"/>" +
        		"</representedOrganization>" +
        		"</asAgent>" +
        		"</device>" +
        		"</sender>" +
        		"<controlActProcess classCode=\"CACT\" moodCode=\"EVN\">" +
        		"<code code=\"PRPA_TE201305UV02\" codeSystemName=\"2.16.840.1.113883.1.6\"/>" +
        		"<authorOrPerformer typeCode=\"AUT\">" +
        		"<assignedPerson classCode=\"ASSIGNED\"/>" +
        		"</authorOrPerformer>" +
        		"<queryByParameter>" +
        		"<queryId root=\"1.263507841149\"/>" +
        		"<statusCode code=\"new\"/>" +
        		"<responseModalityCode code=\"R\"/>" +
        		"<responsePriorityCode code=\"I\"/>" +
        		"<matchCriterionList/>" +
        		"<parameterList>" +
        		"<livingSubjectBirthTime>" +
        		"<value value=\"19501201\"/>" +
        		"<semanticsText/>" +
        		"</livingSubjectBirthTime>" +
        		"<livingSubjectName>" +
        		"<value>" +
        		"<family>NOVAK</family>" +
        		"<given>JAN</given>" +
        		"</value>" +
        		"<semanticsText>LivingSubject.name</semanticsText>" +
        		"</livingSubjectName>" +
        		"<patientAddress>" +
        		"<value/>" +
        		"<semanticsText/>" +
        		"</patientAddress>" +
        		"</parameterList>" +
        		"</queryByParameter>" +
        		"</controlActProcess>" +
        		"</PRPA_IN201305UV02>" +
        		"</soap:Body>" +
        		"</soap:Envelope>";
        
        
        try {
            //String r = SOAPSender.sendMessageSoap("http://office.tiani-spirit.com:6102/SpiritProxy/XCPD", init);
            //String r = SOAPSender.sendMessageSoap("http://jumbo-2.irisa.fr:8080/XCPDRESPSimulator-XCPDRESPSimulator/RespondingGatewayPortTypeImpl?wsdl", init);
            // String r = SOAPSender2.sendToUrlAndGetResponse( "http://jumbo-2.irisa.fr:8080/XCPDRESPSimulator-XCPDRESPSimulator/RespondingGatewayPortTypeImpl?wsdl", rr);
            String r = SOAPSender2.sendToUrlAndGetResponse( "http://office.tiani-spirit.com:6102/SpiritProxy/XCPD", init);
            System.out.println("r = " + r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
