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

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.axis.handlers.BasicHandler;
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.entity.IFEntity;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.handler.data.IFEncryptionHandlingInfo;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.handler.data.IFHandlingInfo;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.NS;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.crypto.EncryptionUtil;

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

/**
 * 
 */
public class BodyEncrypter extends BaseEncrypter {

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

   /**
    * @see org.apache.axis.Handler#invoke(org.apache.axis.MessageContext)
    */
   public void invoke(MessageContext messageContext) throws AxisFault {
      final 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 + " --> BODYENCRYPTER");
      super.invoke(messageContext);
      if (getHandlingInfo().isSuccess()) {
         if (ENCRYPTION_ENABLED) {
            if (logger.isInfoEnabled()) logger.info(fn + "Encryption global ENABLED!");
            if(isXSS4JContentLocal()){
               encryptBodyLocalXSS4J(messageContext, getEncryptingEntity());
            }
         } else {
            if (logger.isInfoEnabled()) logger.info(fn + "Encryption global DISABLED!");
         }
      }else {
         logger.fatal(fn + "Didn't perform operation because HandlingInfo FAILED!");
      }
      if (logger.isDebugEnabled()) logger.debug(fn + " <-- BODYENCRYPTER!");
      MDC.remove(OPTION_LOG_INFO);

   }

   private void encryptBodyLocalXSS4J(MessageContext messageContext, IFEntity encryptingEntity) {
      try {
         Message msg = messageContext.getCurrentMessage();
         SOAPEnvelope soapEnvelope = msg.getSOAPEnvelope();
         Document doc = soapEnvelope.getAsDocument();
         Element envelope = doc.getDocumentElement();
         Element body = (Element) envelope.getElementsByTagNameNS(NS.SOAP_ENVELOPE_NAMESPACE, "Body").item(0);
         EncryptionUtil.encryptXSS4J(doc, body, encryptingEntity);
         String documentString = XMLUtils.DocumentToString(doc);
         StreamSource source = new StreamSource(new StringReader(documentString));
         msg.getSOAPPart().setContent(source);
      } catch (Exception e) {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      }
   }

   public IFEntity getEncryptingEntityFromHandlingInfo() {
      final String fn = "[getEncryptingEntityFromHandlingInfo] ";
      IFEntity result = null;
      IFHandlingInfo handlingInfo = getHandlingInfo();
      if (handlingInfo != null) {
         IFEncryptionHandlingInfo encHandlInf = handlingInfo.getEncryptionHandlingInfoBody();
         if (encHandlInf != null) {
            result = encHandlInf.getEncryptingEntity();
         } else {
            logger.warn(fn + "No encryptionHandlingInfo set for Body in currentThread's handlingInfo!");
         }
      } else {
         logger.warn(fn + "No handlingInfo set in currentThread!");
      }
      return result;
   }
}
