/*
 * Copyright 
 *   2005 axYus - www.axyus.com
 *   2005 L.Meckert - lmeckert@club-internet.fr
 * 
 * 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.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;
import org.w3c.dom.Node;

//import fr.gouv.finances.cp.utils.xml.xpath.XPathExtensionHandler;

/**
 * 
 * 
 */
public class DematTransform {
    private static Logger logger = Logger.getLogger(DematTransform.class);

    public static InputStream transform(InputStream xmlStream, InputStream xslStream, String encoding, Map<String,Object> parameters) throws IOException {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tFactory.newTransformer(new StreamSource(xslStream));
            for(String key:parameters.keySet()) {
                transformer.setParameter(key,parameters.get(key));
            }
        }
        catch (TransformerConfigurationException e) {
            logger.error(e);
            return null;
        }
        ByteArrayOutputStream outArray = new ByteArrayOutputStream();
        try {
            transformer.transform(new StreamSource(xmlStream), new StreamResult(outArray));
        }
        catch (TransformerException e) {
            logger.error(e);
            return null;
        }
        return new ByteArrayInputStream(outArray.toString(encoding).getBytes());
    }
//    public static File saxTransform(InputStream xmlStream, InputStream xslStream, String encoding, Map<String,Object> parameters, File outputFile) throws IOException {
//        TransformerFactory tFactory = null;
//        try {
//            String className = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
//            //String className = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
//            Class clazz = Class.forName(className);
//            Object o = clazz.newInstance();
//            tFactory = (TransformerFactory)o;
//        } catch(Exception ex) {
//            logger.error("while instanciating xalan",ex);
//        }
//        if(tFactory==null) tFactory = TransformerFactory.newInstance();
//logger.debug("tFactory="+tFactory.getClass().getName());
////tFactory.
//        Transformer transformer;
//        try {
//            transformer = tFactory.newTransformer(new StreamSource(xslStream));
//            for(String key:parameters.keySet()) {
//                transformer.setParameter(key,parameters.get(key));
//            }
//        }
//        catch (TransformerConfigurationException e) {
//            logger.error(e);
//            return null;
//        }
//logger.debug("transformer="+transformer.getClass().getName());
////        File fOut = File.createTempFile("xem-", ".xhl");
//        FileOutputStream fos = new FileOutputStream(outputFile);
//        SAXWriter sw = new SAXWriter(fos);
//        try {
////            transformer.transform(new SAXSource(new InputSource(xmlStream)), new StreamResult(fos));
//            transformer.transform(
//                    new SAXSource(new InputSource(xmlStream)), 
//                    new SAXResult(sw)
//            );
//        }
//        catch (TransformerException e) {
//            logger.error(e);
//            return null;
//        }
//        fos.flush(); fos.close();
//        return outputFile;
//    }
    public static InputStream transform(InputStream xmlStream, InputStream xslStream, String encoding) throws IOException {
        return transform(xmlStream, xslStream, encoding, new Hashtable<String,Object>());
    }
    public static InputStream transform(Node xmlNode, InputStream xslStream) throws IOException {
    	return transform(xmlNode,xslStream,new Hashtable<String,Object>());
    }
    public static InputStream transform(Node xmlNode, InputStream xslStream/*, String encoding*/, Map<String,Object> parameters) throws IOException {
//        for(String key:parameters.keySet()) {
//            System.out.println(key+"="+parameters.get(key).toString());
//        }
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tFactory.newTransformer(new StreamSource(xslStream));
//System.out.println("transformer="+transformer.getClass().getName());
            for(String key:parameters.keySet()) {
                transformer.setParameter(key,parameters.get(key));
            }
        }
        catch (TransformerConfigurationException e) {
            logger.error(e);
            e.printStackTrace();
            return null;
        }
        ByteArrayOutputStream outArray = new ByteArrayOutputStream();
        try {
            transformer.transform(new DOMSource(xmlNode), new StreamResult(outArray));
        }
        catch (TransformerException e) {
            logger.error(e);
            e.printStackTrace();
            return null;
        }

        //return new ByteArrayInputStream(outArray.toString(encoding).getBytes());
        return new ByteArrayInputStream(outArray.toByteArray());
    }
//    public static File saxTransform(InputStream xmlStream, InputStream xslStream, String encoding, File outputFile) throws IOException {
//        return saxTransform(xmlStream, xslStream, encoding, new Hashtable<String,Object>(), outputFile);
//    }
//    public static File saxTransform(Node xmlNode, InputStream xslStream) throws IOException {
//    	return saxTransform(xmlNode,xslStream,new Hashtable<String,Object>());
//    }
}
