package net.aocat.siri.proxy.client;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.FileProvider;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.message.SOAPEnvelope;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
 * <p>Title: SIRIProxyClient</p>
 * <p>Description: SIRIProxyClient.</p>
 */
public class SIRIProxyClient
{
	   private static final String MTI_PREFIX = "<procesa xmlns=\"http://www.openuri.org/\"/>";
	
	   public SIRIProxyClient ()
	   {
	   }//SIRIProxyClient
	   
       public FileProvider getWssd () throws Exception
	   {
	      InputStream is = ClassLoader.getSystemResourceAsStream("net/aocat/siri/proxy/client/siri-client-config.wsdd");
	      return new FileProvider(is);
	    	
	   }//getWssd
	    
	   public Element invoca (Element req, URL url, boolean signar) throws Exception
	   {
		 //preparar crida
		 Document xml = ba2dom(MTI_PREFIX.getBytes());
		 Node nReq = xml.importNode(req,true);
		 xml.getDocumentElement().appendChild(nReq);

		 SOAPEnvelope requestEnvelope = new SOAPEnvelope();
	     SOAPBodyElement requestBodyElement = new SOAPBodyElement(xml.getDocumentElement());
	     requestEnvelope.addBodyElement(requestBodyElement);
		 
	     //crida
	     Service service = (!signar)? new Service() : new Service(getWssd());
	     Call call = (Call) service.createCall();

	     //resposta
	     call.setTargetEndpointAddress(url);
	     SOAPEnvelope responseEnvelope = call.invoke(requestEnvelope);

	     SOAPBodyElement responseBody = (SOAPBodyElement) responseEnvelope.getBodyElements().get(0);
	     Element msgOut = responseBody.getAsDOM();

	     return (Element)msgOut.getFirstChild();

	   }//invoca
	
	   private static Document ba2dom (byte[] xmlSource) throws Exception
	   {
	       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	       factory.setNamespaceAware(true);
	       DocumentBuilder builder = factory.newDocumentBuilder();
	       return builder.parse(new ByteArrayInputStream(xmlSource));

	   }//ba2dom
	   
}//SIRIProxyClient
