/*
 * Copyright
 *   2008 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 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.dgfip.xemelios.web.navigate;

import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.common.PJRef;
import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
import fr.gouv.finances.dgfip.xemelios.data.DataImpl;
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;
import java.util.Hashtable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.xpath.XPathFactory;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ViewAttachmentAction extends StdDispatchAction {
    public static final Hashtable<String,String> MIME_TYPES = new Hashtable<String,String>();
    static {

          MIME_TYPES.put(" ","application/octet-stream");
          MIME_TYPES.put("323","text/h323");
          MIME_TYPES.put("acx","application/internet-property-stream");
          MIME_TYPES.put("ai","application/postscript");
          MIME_TYPES.put("aif","audio/x-aiff");
          MIME_TYPES.put("aifc","audio/x-aiff");
          MIME_TYPES.put("aiff","audio/x-aiff");
          MIME_TYPES.put("asf","video/x-ms-asf");
          MIME_TYPES.put("asr","video/x-ms-asf");
          MIME_TYPES.put("asx","video/x-ms-asf");
          MIME_TYPES.put("au","audio/basic");
          MIME_TYPES.put("avi","video/x-msvideo");
          MIME_TYPES.put("axs","application/olescript");
          MIME_TYPES.put("bas","text/plain");
          MIME_TYPES.put("bcpio","application/x-bcpio");
          MIME_TYPES.put("bin","application/octet-stream");
          MIME_TYPES.put("bmp","image/bmp");
          MIME_TYPES.put("c","text/plain");
          MIME_TYPES.put("cat","application/vnd.ms-pkiseccat");
          MIME_TYPES.put("cdf","application/x-cdf");
          MIME_TYPES.put("cer","application/x-x509-ca-cert");
          MIME_TYPES.put("class","application/octet-stream");
          MIME_TYPES.put("clp","application/x-msclip");
          MIME_TYPES.put("cmx","image/x-cmx");
          MIME_TYPES.put("cod","image/cis-cod");
          MIME_TYPES.put("cpio","application/x-cpio");
          MIME_TYPES.put("crd","application/x-mscardfile");
          MIME_TYPES.put("crl","application/pkix-crl");
          MIME_TYPES.put("crt","application/x-x509-ca-cert");
          MIME_TYPES.put("csh","application/x-csh");
          MIME_TYPES.put("css","text/css");
          MIME_TYPES.put("csv","text/csv");
          MIME_TYPES.put("dcr","application/x-director");
          MIME_TYPES.put("der","application/x-x509-ca-cert");
          MIME_TYPES.put("dir","application/x-director");
          MIME_TYPES.put("dll","application/x-msdownload");
          MIME_TYPES.put("dms","application/octet-stream");
          MIME_TYPES.put("doc","application/msword");
          MIME_TYPES.put("dot","application/msword");
          MIME_TYPES.put("dvi","application/x-dvi");
          MIME_TYPES.put("dxr","application/x-director");
          MIME_TYPES.put("eps","application/postscript");
          MIME_TYPES.put("etx","text/x-setext");
          MIME_TYPES.put("evy","application/envoy");
          MIME_TYPES.put("exe","application/octet-stream");
          MIME_TYPES.put("fif","application/fractals");
          MIME_TYPES.put("flr","x-world/x-vrml");
          MIME_TYPES.put("gif","image/gif");
          MIME_TYPES.put("gtar","application/x-gtar");
          MIME_TYPES.put("gz","application/x-gzip");
          MIME_TYPES.put("h","text/plain");
          MIME_TYPES.put("hdf","application/x-hdf");
          MIME_TYPES.put("hlp","application/winhlp");
          MIME_TYPES.put("hqx","application/mac-binhex40");
          MIME_TYPES.put("hta","application/hta");
          MIME_TYPES.put("htc","text/x-component");
          MIME_TYPES.put("htm","text/html");
          MIME_TYPES.put("html","text/html");
          MIME_TYPES.put("htt","text/webviewhtml");
          MIME_TYPES.put("ico","image/x-icon");
          MIME_TYPES.put("ief","image/ief");
          MIME_TYPES.put("iii","application/x-iphone");
          MIME_TYPES.put("ins","application/x-internet-signup");
          MIME_TYPES.put("isp","application/x-internet-signup");
          MIME_TYPES.put("jfif","image/pipeg");
          MIME_TYPES.put("jpe","image/jpeg");
          MIME_TYPES.put("jpeg","image/jpeg");
          MIME_TYPES.put("jpg","image/jpeg");
          MIME_TYPES.put("js","application/x-javascript");
          MIME_TYPES.put("latex","application/x-latex");
          MIME_TYPES.put("lha","application/octet-stream");
          MIME_TYPES.put("lsf","video/x-la-asf");
          MIME_TYPES.put("lsx","video/x-la-asf");
          MIME_TYPES.put("lzh","application/octet-stream");
          MIME_TYPES.put("m13","application/x-msmediaview");
          MIME_TYPES.put("m14","application/x-msmediaview");
          MIME_TYPES.put("m3u","audio/x-mpegurl");
          MIME_TYPES.put("man","application/x-troff-man");
          MIME_TYPES.put("mdb","application/x-msaccess");
          MIME_TYPES.put("me","application/x-troff-me");
          MIME_TYPES.put("mht","message/rfc822");
          MIME_TYPES.put("mhtml","message/rfc822");
          MIME_TYPES.put("mid","audio/mid");
          MIME_TYPES.put("mny","application/x-msmoney");
          MIME_TYPES.put("mov","video/quicktime");
          MIME_TYPES.put("movie","video/x-sgi-movie");
          MIME_TYPES.put("mp2","video/mpeg");
          MIME_TYPES.put("mp3","audio/mpeg");
          MIME_TYPES.put("mpa","video/mpeg");
          MIME_TYPES.put("mpe","video/mpeg");
          MIME_TYPES.put("mpeg","video/mpeg");
          MIME_TYPES.put("mpg","video/mpeg");
          MIME_TYPES.put("mpp","application/vnd.ms-project");
          MIME_TYPES.put("mpv2","video/mpeg");
          MIME_TYPES.put("ms","application/x-troff-ms");
          MIME_TYPES.put("mvb","application/x-msmediaview");
          MIME_TYPES.put("nws","message/rfc822");
          MIME_TYPES.put("oda","application/oda");
          MIME_TYPES.put("p10","application/pkcs10");
          MIME_TYPES.put("p12","application/x-pkcs12");
          MIME_TYPES.put("p7b","application/x-pkcs7-certificates");
          MIME_TYPES.put("p7c","application/x-pkcs7-mime");
          MIME_TYPES.put("p7m","application/x-pkcs7-mime");
          MIME_TYPES.put("p7r","application/x-pkcs7-certreqresp");
          MIME_TYPES.put("p7s","application/x-pkcs7-signature");
          MIME_TYPES.put("pbm","image/x-portable-bitmap");
          MIME_TYPES.put("pdf","application/pdf");
          MIME_TYPES.put("pfx","application/x-pkcs12");
          MIME_TYPES.put("pgm","image/x-portable-graymap");
          MIME_TYPES.put("pko","application/ynd.ms-pkipko");
          MIME_TYPES.put("pma","application/x-perfmon");
          MIME_TYPES.put("pmc","application/x-perfmon");
          MIME_TYPES.put("pml","application/x-perfmon");
          MIME_TYPES.put("pmr","application/x-perfmon");
          MIME_TYPES.put("pmw","application/x-perfmon");
          MIME_TYPES.put("pnm","image/x-portable-anymap");
          MIME_TYPES.put("pot,","application/vnd.ms-powerpoint");
          MIME_TYPES.put("ppm","image/x-portable-pixmap");
          MIME_TYPES.put("pps","application/vnd.ms-powerpoint");
          MIME_TYPES.put("ppt","application/vnd.ms-powerpoint");
          MIME_TYPES.put("prf","application/pics-rules");
          MIME_TYPES.put("ps","application/postscript");
          MIME_TYPES.put("pub","application/x-mspublisher");
          MIME_TYPES.put("qt","video/quicktime");
          MIME_TYPES.put("ra","audio/x-pn-realaudio");
          MIME_TYPES.put("ram","audio/x-pn-realaudio");
          MIME_TYPES.put("ras","image/x-cmu-raster");
          MIME_TYPES.put("rgb","image/x-rgb");
          MIME_TYPES.put("rmi","audio/mid");
          MIME_TYPES.put("roff","application/x-troff");
          MIME_TYPES.put("rtf","application/rtf");
          MIME_TYPES.put("rtx","text/richtext");
          MIME_TYPES.put("scd","application/x-msschedule");
          MIME_TYPES.put("sct","text/scriptlet");
          MIME_TYPES.put("setpay","application/set-payment-initiation");
          MIME_TYPES.put("setreg","application/set-registration-initiation");
          MIME_TYPES.put("sh","application/x-sh");
          MIME_TYPES.put("shar","application/x-shar");
          MIME_TYPES.put("sit","application/x-stuffit");
          MIME_TYPES.put("snd","audio/basic");
          MIME_TYPES.put("spc","application/x-pkcs7-certificates");
          MIME_TYPES.put("spl","application/futuresplash");
          MIME_TYPES.put("src","application/x-wais-source");
          MIME_TYPES.put("sst","application/vnd.ms-pkicertstore");
          MIME_TYPES.put("stl","application/vnd.ms-pkistl");
          MIME_TYPES.put("stm","text/html");
          MIME_TYPES.put("svg","image/svg+xml");
          MIME_TYPES.put("sv4cpio","application/x-sv4cpio");
          MIME_TYPES.put("sv4crc","application/x-sv4crc");
          MIME_TYPES.put("swf","application/x-shockwave-flash");
          MIME_TYPES.put("t","application/x-troff");
          MIME_TYPES.put("tar","application/x-tar");
          MIME_TYPES.put("tcl","application/x-tcl");
          MIME_TYPES.put("tex","application/x-tex");
          MIME_TYPES.put("texi","application/x-texinfo");
          MIME_TYPES.put("texinfo","application/x-texinfo");
          MIME_TYPES.put("tgz","application/x-compressed");
          MIME_TYPES.put("tif","image/tiff");
          MIME_TYPES.put("tiff","image/tiff");
          MIME_TYPES.put("tr","application/x-troff");
          MIME_TYPES.put("trm","application/x-msterminal");
          MIME_TYPES.put("tsv","text/tab-separated-values");
          MIME_TYPES.put("txt","text/plain");
          MIME_TYPES.put("uls","text/iuls");
          MIME_TYPES.put("ustar","application/x-ustar");
          MIME_TYPES.put("vcf","text/x-vcard");
          MIME_TYPES.put("vrml","x-world/x-vrml");
          MIME_TYPES.put("wav","audio/x-wav");
          MIME_TYPES.put("wcm","application/vnd.ms-works");
          MIME_TYPES.put("wdb","application/vnd.ms-works");
          MIME_TYPES.put("wks","application/vnd.ms-works");
          MIME_TYPES.put("wmf","application/x-msmetafile");
          MIME_TYPES.put("wps","application/vnd.ms-works");
          MIME_TYPES.put("wri","application/x-mswrite");
          MIME_TYPES.put("wrl","x-world/x-vrml");
          MIME_TYPES.put("wrz","x-world/x-vrml");
          MIME_TYPES.put("xaf","x-world/x-vrml");
          MIME_TYPES.put("xbm","image/x-xbitmap");
          MIME_TYPES.put("xla","application/vnd.ms-excel");
          MIME_TYPES.put("xlc","application/vnd.ms-excel");
          MIME_TYPES.put("xlm","application/vnd.ms-excel");
          MIME_TYPES.put("xls","application/vnd.ms-excel");
          MIME_TYPES.put("xlt","application/vnd.ms-excel");
          MIME_TYPES.put("xlw","application/vnd.ms-excel");
          MIME_TYPES.put("xof","x-world/x-vrml");
          MIME_TYPES.put("xpm","image/x-xpixmap");
          MIME_TYPES.put("xwd","image/x-xwindowdump");
          MIME_TYPES.put("z","application/x-compress");
          MIME_TYPES.put("zip","application/zip");
    }
    private static final Logger logger = Logger.getLogger(ViewAttachmentAction.class);

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

        // http://localhost:8080/attachment?pjId=200811HPJ100018liq446&collectivite=26620926100012
        String collectivite = request.getParameter("collectivite");
        String pjId = request.getParameter("pjId");
        String method = request.getParameter("method");
        String errorMessage = null;
        
        if(collectivite==null || collectivite.length()==0) throw new IllegalArgumentException("parameter collectivite is not specified");
        if(pjId!=null && collectivite!=null) {
            try {
                DataImpl impl = DataLayerManager.getImplementation();
                PJRef pjRef = null;
                if("byNom".equals(method)) {
                    pjRef = impl.getPj(new Pair(collectivite,""), pjId, user);
                } else {
                    pjRef = impl.getPjByUniqueId(new Pair(collectivite,""), pjId, user);
                }
                if(pjRef!=null) {
                  response.setContentType(getMimeType(pjRef.getFileName()));
                  response.setHeader("Content-Disposition", "attachment; filename="+pjRef.getFileName());
                  response.setContentLength(pjRef.getData().length);
                  response.getOutputStream().write(pjRef.getData());
                  response.getOutputStream().flush();
                  response.getOutputStream().close();
                } else {
                    errorMessage = "Pi&egrave;ce non trouv&eacute;e.";
                }
            } catch(DataConfigurationException dcEx) {
                logger.error("while getting PJ",dcEx);
            } catch(DataAccessException daEx) {
                logger.error("while getting PJ",daEx);
            }
        }
        if(errorMessage!=null) {
            request.setAttribute("error.message", errorMessage);
            return mapping.findForward("simple.error");
        }
        return null;
    }

    public String getMimeType(String filename) {
        String ret = null;
        String ext = null;
        int pos = filename!=null ? filename.lastIndexOf('.') : -1;
        if(pos>=0) {
            ext = filename.substring(pos+1).toLowerCase();

        } else ext = " ";
        ret = MIME_TYPES.get(ext);
        return ret;
    }
}
