/*
 * Copyright
 *   2007 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 Lesser General Public License as published by
 * the Free Software Foundation; either version 3 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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 javax.xml.namespace.NamespaceContext;
import org.apache.log4j.Logger;

/**
 *  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;
    private NamespaceContext nsCtx;

    // Les attributs a renseigner
    /**
     * 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(NamespaceContext nsCtx) {
        this.nsCtx=nsCtx;
        attributes = new Hashtable<Integer, Object>();
    }

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

    /**
     * Evalue le contextte et construir un SignatureVerifier initialise
     * @return un SignatureVerifier de la classe appropriee
     */
    public SignatureVerifier newSignatureVerifier() {
        SignatureVerifier 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);


        logger.debug("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(nsCtx);
                logger.debug(" newSignatureVerifier=> APXSSignatureReporter");
            } else {
                verifier = new APXSSignatureVerifier(nsCtx);
                logger.debug(" newSignatureVerifier=> APXSSignatureVerifier");
            }
        } else {
            if (doPostrait) {
                verifier = null; //NOT IMPLEMENTED TODO throw Excaption new APXSSignatureReporter();
            } else {
                verifier = new LXJNISignatureVerifier();
                logger.debug(" newSignatureVerifier=> LXJNISignatureVerifier");
            }
        }

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

         verifier.setSignatureXPath(signatureXPath != null ? signatureXPath : "//ds:Signature");
        
        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;
    }
}

   
    
    




