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

import de.tu_dresden.diplom.richter_mirko_mat2628335.common.entity.IFEntity;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.handler.data.IFHandlingInfo;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.handler.data.IFSignatureHandlingInfo;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.crypto.SignUtil;
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 javax.xml.transform.stream.StreamSource;
import java.io.StringReader;

/**
 * 
 */
public class CoordinationContextSigner extends BaseSigner {

   private static final Logger logger = Logger.getLogger(CoordinationContextSigner.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) {
         //fn = fn + " -> " + logInfo + "::";
         MDC.put(OPTION_LOG_INFO, logInfo);
      }
      if (logger.isDebugEnabled()) logger.debug(fn + " --> COORDINATIONCONTEXTSIGNER");
      super.invoke(messageContext);
      if (getHandlingInfo().isSuccess()) {
         IFEntity signingEntity = getSigningEntity();
         if (logger.isDebugEnabled()) logger.debug(fn + " signing with entity '" + signingEntity + "'");
         if (isXSS4JEnveloped()) {
            signCoordinationContextEnvelopedXSS4J(messageContext, signingEntity);
         } else if (isTSIKWSSEC()) {

         } else {
            logger.error(fn + "signature-mechanism unknown");
         }
      } else {
         logger.fatal(fn + "Didn't perform operation because HandlingInfo FAILED!");
      }
      if (logger.isDebugEnabled()) logger.debug(fn + " <-- COORDINATIONCONTEXTSIGNER!");
      MDC.remove(OPTION_LOG_INFO);
   }

   private void signCoordinationContextEnvelopedXSS4J(MessageContext messageContext, IFEntity signingEntity) {
      final String fn = "[signCoordinationContextEnvelopedXSS4J] ";
      try {
         Message msg = messageContext.getCurrentMessage();
         SOAPEnvelope soapEnvelope = msg.getSOAPEnvelope();
         Document doc = soapEnvelope.getAsDocument();
         SignUtil.signEnvelopedXSS4J(doc, getCoordinationContextElement(doc), signingEntity);
         String documentString = XMLUtils.DocumentToString(doc);
         StreamSource source = new StreamSource(new StringReader(documentString));
         msg.getSOAPPart().setContent(source);
      } catch (Exception e) {
         logger.fatal(fn + "error while signing coordinationContext!");
         e.printStackTrace();
      }
   }

   public IFEntity getSigningEntityFromHandlingInfo() {
      final String fn = "[getSigningEntityFromHandlingInfo] ";
      IFEntity result = null;
      IFHandlingInfo handlingInfo = getHandlingInfo();
      if (handlingInfo != null) {
         IFSignatureHandlingInfo sigHandlInf = handlingInfo.getSignatureHandlingInfoCoordinationContext();
         if (sigHandlInf != null) {
            result = sigHandlInf.getActingEntity();
         } else {
            logger.warn(fn + "No signatureHandlingInfo set for CoordinationContext in currentThread's handlingInfo!");
         }
      } else {
         logger.warn(fn + "No handlingInfo set in currentThread!");
      }
      return result;
   }

}
