package de.tu_dresden.diplom.richter_mirko_mat2628335.common.handler;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.axis.MessageContext;
import org.apache.axis.AxisFault;
import org.apache.axis.Message;
import org.apache.axis.utils.XMLUtils;
import org.apache.axis.message.SOAPEnvelope;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.handler.data.IFHandlingInfo;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.context.IFCountingContext;

import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;

/**
 * 
 */
public class StepContextWriter extends BaseContextHandler {

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

   /**
    * @see org.apache.axis.Handler#invoke(org.apache.axis.MessageContext)
    */
   public void invoke(MessageContext messageContext) throws AxisFault {
      String fn = "[invoke]";
      String logInfo = (String) getOption(OPTION_LOG_INFO);
      if (logInfo != null) {
         MDC.put(OPTION_LOG_INFO, logInfo);
      }
      if (logger.isDebugEnabled()) logger.debug(fn + " --> STEPCONTEXTWRITER");
      IFHandlingInfo handlingInfo = getHandlingInfo();
      if (handlingInfo.isSuccess()) {
         try {
            Message msg = messageContext.getCurrentMessage();
            SOAPEnvelope soapEnvelope = msg.getSOAPEnvelope();
            createCountingContextInSOAPHeader(soapEnvelope);
            Document doc = soapEnvelope.getAsDocument();
            Element countingContextElement = getCountingContextElement(doc);
            IFCountingContext countingContext = handlingInfo.getCountingContext();
            if (countingContextElement != null) {
               countingContextElement.appendChild(countingContext.getStepContext().makeContextElement(doc, countingContextElement));
               String documentString = XMLUtils.DocumentToString(doc);
               //System.out.println(documentString);
               StreamSource source = new StreamSource(new StringReader(documentString));
               msg.getSOAPPart().setContent(source);
            } else {
               logger.error(fn + "Element CountingContext not present to write StepContext!");
            }
         } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         }
      } else {
         logger.fatal(fn + "Didn't perform operation because HandlingInfo FAILED!");
      }
      if (logger.isDebugEnabled()) logger.debug(fn + " <-- STEPCONTEXTWRITER");
      MDC.remove(OPTION_LOG_INFO);
   }
}
