package com.fractalite.hermes.teldar.Marshaller;



import org.apache.camel.Exchange;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.*;
import java.io.ByteArrayOutputStream;

@Component
public class MarshallingJAXB {

    private static final Logger logger = LoggerFactory.getLogger(MarshallingJAXB.class);


    public MarshallingJAXB() {
    }

    public static String printXML(Object object) {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        JAXBContext jc;
        String output = "";
        try {

            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            jc = JAXBContext.newInstance(object.getClass());
            //Marshaller and properties
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty("jaxb.fragment", Boolean.TRUE);

            marshaller.marshal(object, document);
            SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();

            //Whole envolope of request
            SOAPPart soapPart = soapMessage.getSOAPPart();
            SOAPEnvelope envelope = soapPart.getEnvelope();

            //Teldar namespace uri for prefix
            String serverURI = "http://webservice.gekko-holding.com/v2_4";
            envelope.addNamespaceDeclaration("ns2", serverURI);
            
            
            
          //SOAPBody
            soapMessage.getSOAPBody().addDocument(document);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            soapMessage.writeTo(outputStream);

            output = new String(outputStream.toByteArray());
            return output;


        } catch (Exception e) {
            logger.info(e.toString());
        }

        return null;

    }

    public void marshallObject(Exchange exchange) throws Exception{
        Object objectToMarshall= exchange.getIn().getBody();
        String output = printXML(objectToMarshall);
        exchange.getIn().setBody(output, String.class);
    }


}