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.w3c.dom.Element;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.handler.data.IFHandlingInfo;
import de.tu_dresden.diplom.richter_mirko_mat2628335.common.crypto.VerifyUtil;

/**
 * 
 */
public class StepContextSignatureValidator extends BaseSignatureValidator{

   private static final Logger logger = Logger.getLogger(StepContextSignatureValidator.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 + " --> STEPCONTEXTSIGNATUREVALIDATOR");
      super.invoke(messageContext);
      IFHandlingInfo handlingInfo = getHandlingInfo();
      if (handlingInfo.isSuccess()) {
         try {
            Message message = messageContext.getCurrentMessage();
            //@TODO remove logging-stuff
            if (message == messageContext.getRequestMessage()) {
               if (logger.isDebugEnabled()) logger.debug(fn + " working with request-message");
            } else if (message == messageContext.getResponseMessage()) {
               if (logger.isDebugEnabled()) logger.debug(fn + " working with response-message");
            } else {
               if (logger.isDebugEnabled()) logger.debug(fn + " working neither with request-message nor with response-message");
            }
            Element stepContext = getStepContextElement(message);
            if (stepContext == null) {
               logger.error(fn + " couldn't find stepContext");
               handlingInfo.setResultCode(IFHandlingInfo.STEP_CONTEXT_NOT_FOUND);
            } else {
               VerifyUtil.validateEnvelopedXSS4J(stepContext, handlingInfo.getSignatureHandlingInfoStepContext());
               if (handlingInfo.getSignatureHandlingInfoStepContext().isSuccess()) {
                  //@TODO check if the signature has been made by the wanted Entity!
               }
            }
         } 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 + " <-- STEPCONTEXTSIGNATUREVALIDATOR");
      MDC.remove(OPTION_LOG_INFO);
   }
}
