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

import de.tu_dresden.diplom.richter_mirko_mat2628335.common.crypto.VerifyUtil;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.handler.data.IFHandlingInfo;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.Message;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.w3c.dom.Element;

/**
 * 
 */
public class CoordinationContextSignatureValidator extends BaseSignatureValidator {

   private static final Logger logger = Logger.getLogger(CoordinationContextSignatureValidator.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 + " --> COORDINATIONCONTEXTSIGNATUREVALIDATOR");
      super.invoke(messageContext);
      IFHandlingInfo handlingInfo = getHandlingInfo();
      if (handlingInfo.isSuccess()) {
         try {
            Message message = messageContext.getCurrentMessage();
            Element coordinationContext = getCoordinationContextElement(message);
            if (coordinationContext == null) {
               logger.error(fn + " couldn't find coordinationContext");
               handlingInfo.setResultCode(IFHandlingInfo.COORDINATION_CONTEXT_NOT_FOUND);
            } else {
               VerifyUtil.validateEnvelopedXSS4J(coordinationContext, handlingInfo.getSignatureHandlingInfoCoordinationContext());
               if (handlingInfo.getSignatureHandlingInfoCoordinationContext().isSuccess()) {
                  //@TODO check if the signature has been made by the wanted Witness!
               }
            }
         } 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 + " <-- COORDINATIONCONTEXTSIGNATUREVALIDATOR");
      MDC.remove(OPTION_LOG_INFO);
   }
}
