/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2008 C.Marchand - christophe.marchand@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.dgfip.xemelios.web.utils.filters;

import fr.gouv.finances.dgfip.xemelios.web.utils.CharArrayResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.TransformerFactoryImpl;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

/**
 *
 * @author chm
 */
public class HRefXemeliosFilter implements Filter {

    private static final Logger logger = Logger.getLogger(HRefXemeliosFilter.class);
    private ServletContext servletContext;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.servletContext = filterConfig.getServletContext();
    }

    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (req instanceof HttpServletRequest) {
            HttpServletRequest httpReq = (HttpServletRequest) req;
            HttpServletResponse httpResp = (HttpServletResponse) response;
            //ByteArrayResponseWrapper wrapper = new ByteArrayResponseWrapper(httpResp);
            CharArrayResponseWrapper wrapper = new CharArrayResponseWrapper(httpResp);
            chain.doFilter(req, wrapper);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                char[] inputBuffer = wrapper.toCharArray();
                TransformerFactory tFactory = TransformerFactoryImpl.newInstance();
                File xslFile = new File(servletContext.getRealPath("/js/display/href-converter.xsl"));
                Document doc = builder.parse(new InputSource(new CharArrayReader(inputBuffer)));
                
                Transformer transformer = tFactory.newTransformer(new StreamSource(xslFile));
//              Hashtable<String,Object> params = new Hashtable<String,Object>();
                transformer.setParameter("server",req.getServerName());
                transformer.setParameter("port",req.getServerPort());
                transformer.setParameter("context",httpReq.getContextPath());
                transformer.transform(new DOMSource(doc), new StreamResult(baos));
                baos.flush();
                baos.close();
                byte[] data = baos.toByteArray();
                httpResp.setContentType("text/html");
//              httpResp.setHeader("Content-Disposition", "attachment");
                httpResp.setContentLength(data.length);
                httpResp.getOutputStream().write(data);
                httpResp.getOutputStream().flush();
                httpResp.getOutputStream().close();
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        } else {
            chain.doFilter(req, response);
        }
    }

    public void destroy() {
    }
}
