/*
 * Copyright
 *   2008 axYus - www.axyus.com
 *   2008 L.Meckert - laurent.meckert@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package fr.gouv.finances.cp.xemelios.plugin.signature;

import java.util.Hashtable;
import org.apache.log4j.Logger;
import java.io.File;
import javax.xml.namespace.NamespaceContext;

/**
 *  Selon le contexte, construit une instance de la sous classe appropriee
 *  de SignatureVerifier
 * @author laurent.meckert
 */
public class SignatureVerifierFactory {

  static Logger logger = Logger.getLogger(SignatureVerifierFactory.class);
  private Hashtable<Integer, Object> attributes;  // Les attributs a renseigner
   private NamespaceContext nsCtx; // ns a passer au signatureVerifier

  /**
   * La taille maximum au dessus de laquelle on renonce au "pur java"
   */
  public static int MAX_FILE_SIZE_APACHEXMLSEC = 0;
  /**
   * la taille du fichier choisi
   */
  public static int ACTUAL_FILE_SIZE = 1;
  /**
   * force l'utlisation librairie apache
   */
  public static int USE_APACHEXMLSEC = 2;
  /**
   * force l'utilisation de libxml
   */
  public static int USE_LIBXML2 = 3;
  /**
   * force le posttraitement
   */
  public static int DO_POSTTRAIT = 4;
  /**
   * force prise en compte schema ou DTD
   */
  public static int VALIDATE_SCHEMA_OR_DTD = 5;
  /**
   * chemin du DTD externe (concerne seulement libxml)
   */
  public static int EXTERNAL_DTD = 6;
  /**
   *  XPath de la signature 
   */
  public static int SIGNATURE_XPATH = 7;

  /**
   *  Constructeur rprivate sans parametre
   */
  protected SignatureVerifierFactory() {
    attributes = new Hashtable<Integer, Object>();
  }

  /**
   * Constructeur public
   * @return une nouvelle instance
   */
  public static SignatureVerifierFactory newInstance() {
    SignatureVerifierFactory svf = new SignatureVerifierFactory();
    return svf;
  }
   public void setNsCtx(NamespaceContext ctx) {
      nsCtx = ctx;
   }

  protected ISignatureVerifier getSignatureVerifierByName(String svName) {
    try {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      if (loader == null) {
        loader = getClass().getClassLoader();
      }
      Class scClass = Class.forName(svName, true, loader);
      ISignatureVerifier sv = (ISignatureVerifier) (scClass.newInstance());
      return sv;
    } catch (ClassNotFoundException cnfe) {
      cnfe.printStackTrace();
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } catch (Error e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * Evalue le contextte et construir un SignatureVerifier initialise
   * @return un SignatureVerifier de la classe appropriee
   * @throws java.lang.Exception 
   */
  public ISignatureVerifier newSignatureVerifier() throws Exception {
    ISignatureVerifier verifier;
    // part a la paeche aux atributs.
    // si on a force apache 
    boolean useApache = getAttributeAsBoolean(USE_APACHEXMLSEC);
    boolean useLibXml = getAttributeAsBoolean(USE_LIBXML2);
    boolean doPostrait = getAttributeAsBoolean(DO_POSTTRAIT);
    boolean doSchemaValidation = getAttributeAsBoolean(VALIDATE_SCHEMA_OR_DTD);

    String externalDTD = getAttributeAsString(EXTERNAL_DTD);
    String signatureXPath = getAttributeAsString(SIGNATURE_XPATH);

    int maxFileSizeApacheXmlSec = getAttributeAsInt(MAX_FILE_SIZE_APACHEXMLSEC);
    int actualFileSize = getAttributeAsInt(ACTUAL_FILE_SIZE);


    //  System.out.println("Max = " + maxFileSizeApacheXmlSec + ", Actual=" + actualFileSize);

    // A priori on utilise la lib Apache sauf si ocntre indication  
    if (useApache && useLibXml) {
      // pas les 2 a la fois 
      useLibXml = false;
    }
    if (!useApache && !useLibXml) {
      // pas les 2 a la fois 
      useApache = true;
    }
    if (useApache && maxFileSizeApacheXmlSec != Integer.MIN_VALUE && actualFileSize != Integer.MIN_VALUE) {
      if (actualFileSize > maxFileSizeApacheXmlSec) {
        useApache = false;
        useLibXml = true;
      }
    }

    if (useApache) {

      if (doPostrait) {
        //   verifier = new APXSSignatureReporter();
        verifier = this.getSignatureVerifierByName("fr.gouv.finances.cp.xemelios.plugin.signature.APXSSignatureReporter");
      } else {
        //       verifier = new APXSSignatureVerifier();
        verifier = this.getSignatureVerifierByName("fr.gouv.finances.cp.xemelios.plugin.signature.APXSSignatureVerifier");

//  System.out.println(" newSignatureVerifier=> APXSSignatureVerifier");
      }
    } else {
      if (doPostrait) {
        return null; //NOT IMPLEMENTED TODO throw Excaption new LXJNISignatureReporter();
      } else {
        // libxml2 ne sait pas exploiter le schema pour les ID il lui faut
        // absolument un DTD externe
        if (doSchemaValidation && (externalDTD == null)) {
          // Verifier que le DTD existe
          File DTDFile = new File(externalDTD);
          if (DTDFile.exists()) {
            //        verifier = new LXJNISignatureVerifier();
            verifier = this.getSignatureVerifierByName("fr.gouv.finances.cp.xemelios.plugin.signature.LXJNISignatureVerifier");

          } else {
            return null;
          }
        } else {
          //  verifier = new LXJNISignatureVerifier();
          verifier = this.getSignatureVerifierByName("fr.gouv.finances.cp.xemelios.plugin.signature.LXJNISignatureVerifier");

        }
      }
    }
    verifier.setExternalDTD(externalDTD != null ? externalDTD : "");
    verifier.setDoSchemaValidation(doSchemaValidation);

    verifier.setSignatureXPath(signatureXPath != null ? signatureXPath : "//ds:Signature");
    verifier.setNsCtx( nsCtx);


    System.out.println(verifier.getClass().getName());
    return verifier;
  }

  /**
   * set un attribut String
   * @param attribute
   * @param value 
   */
  public void setAttribute(int attribute, String value) {
    attributes.put(new Integer(attribute), value);
  }

  /**
   * set un attribut int
   * @param attribute
   * @param value
   */
  public void setAttribute(int attribute, int value) {
    attributes.put(new Integer(attribute), new Integer(value));
  }

  /**
   * set un attribut boolean
   * @param attribute
   * @param value
   */
  public void setAttribute(int attribute, boolean value) {
    attributes.put(new Integer(attribute), new Boolean(value));
  }

  /**
   * 
   * @param attribute
   * @return la valeur qui a ete stocke pour cet attribut ou null
   */
  public Object getAttribute(int attribute) {
    if (attributes.containsKey(attribute)) {
      return attributes.get(attribute);
    } else {
      return null;
    }
  }

  /**
   * 
   * @param attribute
   * @return la valeur qui a ete stocke pour cet attribut ou null
   */
  public boolean getAttributeAsBoolean(int attribute) {
    if (attributes.containsKey(attribute)) {
      Object o = attributes.get(attribute);
      if (o instanceof java.lang.Boolean) {
        return ((Boolean) o).booleanValue();
      }
    }
    return false;
  }

  /**
   * 
   * @param attribute
   * @return la valeur qui a ete stocke pour cet attribut ou null
   */
  public int getAttributeAsInt(int attribute) {
    if (attributes.containsKey(attribute)) {
      Object o = attributes.get(attribute);
      if (o instanceof java.lang.Integer) {
        return ((Integer) o).intValue();
      }
    }
    return Integer.MIN_VALUE; // par convention en guise de  NAN ..
  }

  /**
   * 
   * @param attribute
   * @return la valeur qui a ete stocke pour cet attribut ou null
   */
  public String getAttributeAsString(int attribute) {
    if (attributes.containsKey(attribute)) {
      Object o = attributes.get(attribute);
      if (o instanceof java.lang.String) {
        return (String) o;
      }
    }
    return null;
  }
}

   
    
    




