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 CountingContextSignatureValidator extends BaseSignatureValidator{

   private static final Logger logger = Logger.getLogger(CountingContextSignatureValidator.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 + " --> COUNTINGCONTEXTSIGNATUREVALIDATOR");
      super.invoke(messageContext);
      IFHandlingInfo handlingInfo = getHandlingInfo();
      if (handlingInfo.isSuccess()) {
         try {
            Message message = messageContext.getCurrentMessage();
            Element countingContext = getCountingContextElement(message);
            if (countingContext == null) {
               logger.error(fn + " couldn't find countingContext");
               handlingInfo.setResultCode(IFHandlingInfo.COUNTING_CONTEXT_NOT_FOUND);
            } else {
               VerifyUtil.validateEnvelopedXSS4J(countingContext, handlingInfo.getSignatureHandlingInfoCountingContext());
               if (handlingInfo.getSignatureHandlingInfoCountingContext().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 + " <-- COUNTINGCONTEXTSIGNATUREVALIDATOR");
      MDC.remove(OPTION_LOG_INFO);
   }
}
