/**
 * AuthenticationHandler.java 
 */
package com.jammconsulting.channelAdvisor;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import org.apache.axis.*;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.log4j.Logger;

/**
 * Handler for authentication to ChannelAdvisor API
 */
@SuppressWarnings("serial")
public class AuthenticationHandler extends BasicHandler {
  /** The developer key to use */
  private static String developerKey;
  /** The password to use */
  private static String password;
  
  /** Invoke this hander */
  public void invoke(MessageContext context) throws AxisFault {
    Logger.getLogger(getClass()).fatal("In invoke");
    try {
      MessageContext smc = (MessageContext) context;
      SOAPMessage message = smc.getMessage();
      QName APICredentialsName = new QName("http://api.channeladvisor.com/webservices/","APICredentials");
      QName DeveloperKeyName = new QName("http://api.channeladvisor.com/webservices/","DeveloperKey");
      QName PasswordName = new QName("http://api.channeladvisor.com/webservices/", "Password");

      SOAPHeader header = message.getSOAPHeader();
      SOAPHeaderElement cred = new SOAPHeaderElement(APICredentialsName);
      SOAPHeaderElement key = new SOAPHeaderElement(DeveloperKeyName);
      key.setObjectValue(developerKey);
      SOAPHeaderElement pw = new SOAPHeaderElement(PasswordName);
      pw.setObjectValue(password);
      cred.addChildElement(key);
      cred.addChildElement(pw);
      header.appendChild(cred);
    } catch (Exception e) {
      throw new AxisFault("Error during authentication", e);
    }
  }

  /**
   * @param developerKey the developerKey to set
   */
  public static void setDeveloperKey(String developerKey) {
    AuthenticationHandler.developerKey = developerKey;
  }

  /**
   * @param password the password to set
   */
  public static void setPassword(String password) {
    AuthenticationHandler.password = password;
  } 
}
