/*
 * 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.navigate;

import java.io.BufferedInputStream;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import sun.nio.cs.ext.MS932DB.Encoder;

import fr.gouv.finances.dgfip.utils.Base64;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.common.NetAccess;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.dgfip.xemelios.web.AttributeHelper;
import fr.gouv.finances.dgfip.xemelios.web.utils.StdDispatchAction;

public class PjAtlasAction extends StdDispatchAction {
    private static final Logger logger = Logger.getLogger(PjAtlasAction.class);

    @Override
    public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug(request.getQueryString());
        HttpSession session = request.getSession();
        XemeliosUser user = AttributeHelper.getUser(session);
        XPathFactory xpf = XPathFactory.newInstance();

        // http[s]://URL_SMA:PORT_SMA/archive_link/composant/downloadComposantService.do
        // &contRep  : Obligatoire, identifiant SAP du repository dans lequel est stocké le composant,
        // &docId    : Obligatoire, identifiant SAP du document,
        // &compId   : Obligatoire, identifiant SAP du composant,
        // &applyXsl : Optionnel, lorsqu'il est renseigné (peut importe sa valeur),
        
        String contRep = request.getParameter("contRep");
        String docId = request.getParameter("docId");
        
        if(contRep==null || contRep.length()==0) throw new IllegalArgumentException("Le paramètre contRep n'est pas spécifié");
        if(contRep!=null && contRep.length()!=2) throw new IllegalArgumentException(contRep+" n'est pas un compte de repositionnement valide !");
        
        if(docId==null || docId.length()==0) throw new IllegalArgumentException("Le paramètre docId n'est pas spécifié");
        if(docId!=null && docId.length()!=32) throw new IllegalArgumentException(docId+" n'est pas un Id de PJ valide !");
                
        StringBuffer url = new StringBuffer(DataLayerManager.getImplementation().getParameterValue("url.pj.atlas"));
        url.append("?contRep=").append(contRep).append("&docId=").append(docId).append("&applyXsl=true");
        
        //return new ActionForward(url.toString());
        
        
        HttpClient client = NetAccess.getHttpClient();
        URI uri = new URI(url.toString(), true);
        logger.debug("uri="+uri.getPath());
        
        GetMethod method = new GetMethod();
        method.setURI(uri);
        //method.addRequestHeader("Pragma", "no-cache");
        
        int httpRet = client.executeMethod(method);
        if(httpRet>300){
        	String urlError = AttributeHelper.getPreviousView(session).concat("&xsl:param=(error.message,").concat("PJ Introuvable").concat(")");
            return new ActionForward(urlError);
        	//throw new Exception(method.getStatusText());
        } else {
        InputStream is = method.getResponseBodyAsStream();
        
        ServletOutputStream sos = response.getOutputStream();        
        for(Header head:method.getResponseHeaders()){
        	response.setHeader(head.getName(), head.getValue());
        	//System.out.println(head.getName()+"="+head.getValue());
        }
                
        //response.setContentType("application/pdf");
        //response.addHeader("Content-Disposition", meth.getResponseHeader("Content-Disposition").getValue());
        
        BufferedInputStream buf = new BufferedInputStream(is);
    	int readBytes = 0;

    	//read from the file; write to the ServletOutputStream
    	while ((readBytes = buf.read()) != -1){
    		sos.write(readBytes);
    	}
    	sos.flush();sos.close();
    	buf.close();
    	is.close();
    	
    	
        /*InputStream is = meth.getResponseBodyAsStream();
        
        try {	     
        	File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        	tmpDir = new File(tmpDir,Constants.NOM_APP);
        	tmpDir.mkdirs();
        	
        	ServletOutputStream sos = response.getOutputStream();
        	response.setContentType("application/pdf");
        	response.addHeader("Content-Disposition", "attachment; filename="+ pdfFile.getName());

        	BufferedInputStream buf = new BufferedInputStream(new FileInputStream(pdfFile));
        	int readBytes = 0;

        	//read from the file; write to the ServletOutputStream
        	while ((readBytes = buf.read()) != -1){
        		sos.write(readBytes);
        	}
        	sos.flush();sos.close();
        	buf.close();

        } catch(IOException ioEx) {
        	logger.error("while printing to PDF: ",ioEx);
        } catch(DocumentException docEx) {
        	logger.error("while printing to PDF: ",docEx);
        }
        */
        return null;
        }
    }
}
