/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2009 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.exports;

import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import fr.gouv.finances.dgfip.xemelios.export.ExportJob;
import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
import fr.gouv.finances.dgfip.xemelios.web.AttributeHelper;
import fr.gouv.finances.dgfip.xemelios.web.utils.StdDispatchAction;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class GetExportResult extends StdDispatchAction {
    private static final Logger logger = Logger.getLogger(GetExportJobs.class);
    public static final int BUFFER_SIZE = 1024*4;

    protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.debug("in GetExportResult");
        XemeliosUser user = AttributeHelper.getUser(request.getSession());
        try {
            String sTmp = request.getParameter("exportId");
            Long exportId = 0L;
            try {
                exportId = Long.parseLong(sTmp);
            } catch(Exception ex) {
                logger.error("unspecified(ActionMapping,ActionForm,HttpServletRequest,HttpServletResponse)",ex);
                return mapping.findForward("error");
            }
            ExportJob job = DataLayerManager.getImplementation().getExportJob(exportId);
            if(job!=null) {
                if((job.getStatus()==ExportJob.STATUS_TERMINATED || job.getStatus()==ExportJob.STATUS_DOWNLOADED) && job.getStatus()!=ExportJob.STATUS_CLEANED) {
                    String fileName=job.getGeneratedFileName();
                    String ext = fileName.substring(fileName.lastIndexOf('.'));
                    File result = new File(fileName);
                    if(result.exists()) {
                        response.addHeader("Content-disposition", "attachment; filename="+result.getName());
                        response.setContentLength((int)result.length());
                        byte[] buffer = new byte[BUFFER_SIZE];
                        int read = -1;
                        FileInputStream fis = new FileInputStream(result);
                        while((read=fis.read(buffer))>0) {
                            response.getOutputStream().write(buffer, 0, read);
                        }
                        response.getOutputStream().flush();
                        fis.close();
                        Connection con = null;
                        try {
                            con = PoolManager.getInstance().getConnection();
                            String sql = "UPDATE EXPORT_JOBS SET DOWNLOAD_DATE=NOW(), STATUS=? WHERE EXPORT_ID=?";
                            PreparedStatement ps = con.prepareStatement(sql);
                            ps.setInt(1,ExportJob.STATUS_DOWNLOADED);
                            ps.setLong(2, exportId);
                            ps.executeUpdate();
                        } catch(SQLException sqlEx) {
                            logger.error("while updating job status",sqlEx);
                        } finally {
                            if(con!=null) PoolManager.getInstance().releaseConnection(con);
                            con = null;
                        }
                    }
                }
            }
        } catch(Exception ex) {
            logger.error("",ex);
        }
        return null;
    }

}
