/*
 * Copyright
 *   2008 axYus - www.axyus.com
 *   2008 L.Meckert - laurent.meckert.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
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.gouv.finances.cp.xemelios.plugin.signerfichier;

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 FileSigner
 * @author laurent.meckert
 */
public class FileSignerFactory {

   static Logger logger = Logger.getLogger(FileSignerFactory.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 FileSignerFactory() {
    attributes = new Hashtable<Integer, Object>();
  }



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


  protected IFileSigner getFileSignerByName(String svName) {
    try {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      if (loader == null) {
        loader = getClass().getClassLoader();
      }
      Class scClass = Class.forName(svName, true, loader);
      IFileSigner sv = (IFileSigner) (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 FileSigner initialise
   * @return un FileSigner de la classe appropriee
   * @throws java.lang.Exception 
   */
  public IFileSigner newFileSigner() throws Exception {
    IFileSigner signer = null;
    // 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) {
       signer = this.getFileSignerByName("fr.gouv.finances.cp.xemelios.plugin.signerfichier.APXSFileSigner");

    } 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()) {
//             signer = this.getFileSignerByName("fr.gouv.finances.cp.xemelios.plugin.signature.LXJNIFileSigner");

//           } else {
//             return null;
//           }
//         } else {
//           signer = this.getFileSignerByName("fr.gouv.finances.cp.xemelios.plugin.signature.LXJNIFileSigner");

//         }
    }
  

    signer.setNsCtx( nsCtx);

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

  /**
   * 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;
  }
}

   
    
    





