package gov.va.med.esr.jms.vadir.inboundRequest;

import gov.va.med.esr.jms.vadir.StubTranslationService;
import gov.va.med.esr.jms.vadir.outboundResponse.VadirServiceResponseWrapper;
import gov.va.med.esr.mvc.model.GetEESummaryRequest;
import gov.va.schema.militaryhistoryservice.GetMilitaryHistoryResponse;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.ws.client.core.WebServiceTemplate;

public class Jaxb2Test extends AbstractBrokerTestCase {

	
	    private static final String FILE_NAME = "test/vadir/resources/vadir.xsd";
	    private GetEESummaryRequest eeRequest = new GetEESummaryRequest();
	    private WebServiceTemplate vadirWebServiceTemplate = null;
		@Autowired
		private StubTranslationService stubTranslationService;	    
	    private Marshaller vadirMarshaller = null;
	    private Unmarshaller unmarshaller = null;
	    private JmsTemplate inboundJmsTemplate = null;
		public Jaxb2Test(String name) {
			super(name);
		}
	    public void setMarshaller(Marshaller marshaller) {
	        this.vadirMarshaller = marshaller;
	    }

	    public void setUnmarshaller(Unmarshaller unmarshaller) {
	        this.unmarshaller = unmarshaller;
	    }

		public Marshaller createMarshaller() throws Exception {
			Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
			
			String currDir = System.getenv("user.dir");
			
			System.out.println(" Curr Dir = " + currDir);
			
			Class[] classesToBeBound = new Class[1];
			classesToBeBound[0] = gov.va.med.esr.mvc.model.GetEESummaryRequest.class;

			marshaller.setClassesToBeBound(classesToBeBound);
			marshaller.setSchema(new FileSystemResource("D:\\bea\\projects\\ESR.3.0.0\\DNS   kavurt_HECMS_Websrv_1\\vobs\\HECMS_websrv\\src\\main\\webapp\\WEB-INF\\eeSummary.xsd") );
			
			marshaller.afterPropertiesSet();
			return marshaller;
		}

		public Unmarshaller createUnMarshaller() throws Exception {
			Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
			Class[] classesToBeBound = new Class[1];
			classesToBeBound[0] = gov.va.schema.militaryhistory.MilitaryHistory.class;
			marshaller.setClassesToBeBound(classesToBeBound);
			marshaller.setSchema(new FileSystemResource("D:\\bea\\projects\\ESR.3.0.0\\DNS   kavurt_HECMS_Websrv_1\\vobs\\HECMS_websrv\\src\\main\\webapp\\WEB-INF\\eeSummary.xsd") );
			
			marshaller.afterPropertiesSet();
			return marshaller;
		}
		public Unmarshaller createVadirUnMarshaller() throws Exception {
			Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
			Class[] classesToBeBound = new Class[1];
			classesToBeBound[0] = gov.va.schema.militaryhistory.MilitaryHistory.class;
			marshaller.setClassesToBeBound(classesToBeBound);
			marshaller.setSchema(new FileSystemResource("test/vadir/resources/ESRMilitaryHistory.xsd") );
			marshaller.afterPropertiesSet();
			return marshaller;
		}
	    public void saveSettings() throws Exception {
	        FileOutputStream os = null;
	        try {
	            os = new FileOutputStream(FILE_NAME);
	            
	            eeRequest.setKey("1111V11111100");
	            eeRequest.setKeyType("VPID");
	            
	            this.vadirMarshaller.marshal(eeRequest, new StreamResult(os));
	        } finally {
	            if (os != null) {
	                os.close();
	            }
	        }
	    }
	    
	    public void testGo2() throws Exception{
	    	simpleSend(375310940L, 373971922L);
	    }

	    public void simpleSend(long requestId, long personId) throws Exception {
	    	final VadirServiceResponseWrapper responseWrapper = createMinimalWrapper(personId, requestId, this.applicationContext);
	    	JmsTemplate template = (JmsTemplate)this.applicationContext.getBean("inboundJmsTemplate");
	    	template.send(new MessageCreator() {
	    		public Message createMessage(Session session) throws JMSException {
	    			ObjectMessage message = session.createObjectMessage(responseWrapper);
	    			message.setStringProperty("Message_Type", "MSDS");
	    			return message;
	    		}
	    	});
	    }
	    
	    public JmsTemplate getInboundJmsTemplate() {
			return inboundJmsTemplate;
		}
		public void setInboundJmsTemplate(JmsTemplate inboundJmsTemplate) {
			this.inboundJmsTemplate = inboundJmsTemplate;
		}
		public gov.va.med.esr.jms.vadir.outboundResponse.VadirServiceResponseWrapper createMinimalWrapper(long person_id, long trans_id, ApplicationContext applicationContext) throws Exception {
	    	gov.va.med.esr.jms.vadir.outboundResponse.VadirServiceResponseWrapper wrapper = 
	    		new gov.va.med.esr.jms.vadir.outboundResponse.VadirServiceResponseWrapper();
			wrapper.setResponseType(gov.va.med.esr.jms.vadir.outboundResponse.VadirServiceResponseType.NORMAL);		
			wrapper.setPersonId(person_id);
			wrapper.setRequestId(trans_id);
	    	FileInputStream is = new FileInputStream("test/vadir/resources/vadr.xml");
	    	this.setVadirWebServiceTemplate((WebServiceTemplate)applicationContext.getBean("vadirWebServiceTemplate"));	        
	    	Class[] classesToBeBound = new Class[1];
	    	classesToBeBound[0] = gov.va.schema.militaryhistory.MilitaryHistory.class;
	    	Jaxb2Marshaller marshaller = (Jaxb2Marshaller)this.getVadirMarshaller();
	    	marshaller.setClassesToBeBound(classesToBeBound);	            
	    	marshaller.setSchema(new FileSystemResource("test/vadir/resources/ESRMilitaryHistory.xml") );

	       	SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
	    	SOAPConnection connection = soapConnFactory.createConnection();
	    	MessageFactory messageFactory = MessageFactory.newInstance();
	    	SOAPMessage message = messageFactory.createMessage();
	    	SOAPPart soapPart = message.getSOAPPart();
	    	SOAPEnvelope envelope = soapPart.getEnvelope();
	    	SOAPBody body = envelope.getBody();
	    	StreamSource preppedMsgSrc = new StreamSource(new FileInputStream("test/vadir/resources/vadr.xml"));
	    	GetMilitaryHistoryResponse obj = (GetMilitaryHistoryResponse)((Unmarshaller)marshaller).unmarshal(
	    			new StreamSource(new FileInputStream("test/vadir/resources/vadr.xml")));
	    	System.out.println("obj type=" +obj.getClass());
	    	System.out.println("here="+((Unmarshaller)marshaller).unmarshal(
	    			new StreamSource(new FileInputStream("test/vadir/resources/vadr.xml"))));
	    	gov.va.schema.militaryhistory.MilitaryHistory mh = obj.getGetMilitaryHistoryReturn();
	    	System.out.println("Key is : " + mh.getQueryId());
	

  		    gov.va.med.esr.jms.vadir.outboundResponse.model.militaryHistory.MilitaryHistory esrMilitaryHistory = stubTranslationService
						.translate(mh);
				
	    	if (is != null) {
	    		is.close();
	    	}

			wrapper.setResult(esrMilitaryHistory);
		
			return wrapper;
		} 
	    public void testUnMarshaller() throws Exception {
	    	FileInputStream is = new FileInputStream("test/vadir/resources/vadr.xml");
	    	this.setVadirWebServiceTemplate((WebServiceTemplate)applicationContext.getBean("vadirWebServiceTemplate"));	        
	    	Class[] classesToBeBound = new Class[1];
	    	classesToBeBound[0] = gov.va.schema.militaryhistory.MilitaryHistory.class;
	    	Jaxb2Marshaller marshaller = (Jaxb2Marshaller)this.getVadirMarshaller();
	    	marshaller.setClassesToBeBound(classesToBeBound);	            
	    	marshaller.setSchema(new FileSystemResource("test/vadir/resources/ESRMilitaryHistory.xml") );
	    	/////////////////////////
	       	SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
	    	SOAPConnection connection = soapConnFactory.createConnection();
	    	MessageFactory messageFactory = MessageFactory.newInstance();
	    	SOAPMessage message = messageFactory.createMessage();
	    	SOAPPart soapPart = message.getSOAPPart();
	    	SOAPEnvelope envelope = soapPart.getEnvelope();
	    	SOAPBody body = envelope.getBody();
	    	StreamSource preppedMsgSrc = new StreamSource(new FileInputStream("test/vadir/resources/vadr.xml"));
	    //	soapPart.setContent(preppedMsgSrc);
	    	
	    //	message.saveChanges();	    	
	    	/////////////////////////
	    	GetMilitaryHistoryResponse obj = (GetMilitaryHistoryResponse)((Unmarshaller)marshaller).unmarshal(
	    			new StreamSource(new FileInputStream("test/vadir/resources/vadr.xml")));
	    	System.out.println("obj type=" +obj.getClass());
	    	System.out.println("here="+((Unmarshaller)marshaller).unmarshal(new StreamSource(new FileInputStream("test/vadir/resources/vadr.xml"))));
	    	gov.va.schema.militaryhistory.MilitaryHistory mh = obj.getGetMilitaryHistoryReturn();
	    	System.out.println("Key is : " + mh.getQueryId());
	

  		    gov.va.med.esr.jms.vadir.outboundResponse.model.militaryHistory.MilitaryHistory esrMilitaryHistory = stubTranslationService
						.translate(mh);
				
	    	if (is != null) {
	    		is.close();
	    	}
	  	    
	    }
	    public void testSoap() throws Exception {
	    	SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
	    	SOAPConnection connection = soapConnFactory.createConnection();
	    	MessageFactory messageFactory = MessageFactory.newInstance();
	    	SOAPMessage message = messageFactory.createMessage();
	    	SOAPPart soapPart = message.getSOAPPart();
	    	SOAPEnvelope envelope = soapPart.getEnvelope();
	    	SOAPBody body = envelope.getBody();
	    	SOAPElement bodyElement = body.addChildElement(envelope.createName("getPrice", "nsl", "urn:xmethods-BNPriceCheck"));
	    	bodyElement.addChildElement("isbn").addTextNode("0672324229");
	    	message.saveChanges();
	    	System.out.println("\nREQUEST:\n");
	    	
	    	TransformerFactory transformerFactory =TransformerFactory.newInstance();
	    	Transformer transformer = transformerFactory.newTransformer();
	    	Source sourceContent = message.getSOAPPart().getContent();
	    	StreamResult result = new StreamResult(System.out);
	    	transformer.transform(sourceContent, result);
	    	System.out.println();
	    	connection.close();
			
	    }	    
	    
	    public void testSoapFromVadir() throws Exception {
	    	SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
	    	SOAPConnection connection = soapConnFactory.createConnection();
	    	MessageFactory messageFactory = MessageFactory.newInstance();
	    	SOAPMessage message = messageFactory.createMessage();
	    	SOAPPart soapPart = message.getSOAPPart();
	    	SOAPEnvelope envelope = soapPart.getEnvelope();
	    	SOAPBody body = envelope.getBody();
	    	SOAPElement bodyElement = body.addChildElement(envelope.createName("getPrice", "nsl", "urn:xmethods-BNPriceCheck"));
	    	bodyElement.addChildElement("isbn").addTextNode("0672324229");
	    	message.saveChanges();
	    	System.out.println("\nREQUEST:\n");
	    	TransformerFactory transformerFactory =TransformerFactory.newInstance();
	    	Transformer transformer = transformerFactory.newTransformer();
	    	Source sourceContent = message.getSOAPPart().getContent();
	    	StreamResult result = new StreamResult(System.out);
	    	transformer.transform(sourceContent, result);
	    	
	    	System.out.println();
	    	connection.close();            
	    }	    
	    public void testSoapFromSample() throws Exception {
	    	SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
	    	SOAPConnection connection = soapConnFactory.createConnection();
	    	MessageFactory messageFactory = MessageFactory.newInstance();
	    	SOAPMessage message = messageFactory.createMessage();
	    	SOAPPart soapPart = message.getSOAPPart();
	    	SOAPEnvelope envelope = soapPart.getEnvelope();
	    	SOAPBody body = envelope.getBody();
	    	StreamSource preppedMsgSrc = new StreamSource(new FileInputStream("test/vadir/resources/jsmith.xml"));
	    	soapPart.setContent(preppedMsgSrc);
	    	
	    	message.saveChanges();
	    	System.out.println("\nREQUEST:\n");
	    	TransformerFactory transformerFactory =TransformerFactory.newInstance();
	    	Transformer transformer = transformerFactory.newTransformer();
	    	Source sourceContent = message.getSOAPPart().getContent();
	    	StreamResult result = new StreamResult(System.out);
	    	transformer.transform(sourceContent, result);
	    	System.out.println();
	    	System.out.println("output="+result);
	    	connection.close();	    	
	    }	    
	    	    
	    public void loadSettings() throws Exception {
	        FileInputStream is = null;
	        try {
	        	
	            is = new FileInputStream(FILE_NAME);
	            this.eeRequest = (GetEESummaryRequest) ((Unmarshaller)this.vadirMarshaller).unmarshal(new StreamSource(is));
	            System.out.println("Key is : " + eeRequest.getKey());
	            System.out.println("Key Type is : " + eeRequest.getKeyType());
	            
	            
	        } finally {
	            if (is != null) {
	                is.close();
	            }
	        }
	    }
		public WebServiceTemplate getVadirWebServiceTemplate() {
			return vadirWebServiceTemplate;
		}
		@Autowired
		@Required
		public void setVadirWebServiceTemplate(
				WebServiceTemplate vadirWebServiceTemplate) {
			this.vadirWebServiceTemplate = vadirWebServiceTemplate;
		}
		public Marshaller getVadirMarshaller() {
			return vadirMarshaller;
		}
		@Autowired
		@Required
		public void setVadirMarshaller(Marshaller vadirMarshaller) {
			this.vadirMarshaller = vadirMarshaller;
		}
		public Unmarshaller getUnmarshaller() {
			return unmarshaller;
		}
}
