/*
 * 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.batch.exports.postProcessors;

import fr.gouv.finances.dgfip.xemelios.batch.PostProcessor;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import fr.gouv.finances.dgfip.xemelios.export.ExportJob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.log4j.Logger;

/**
 *
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class Zipper implements PostProcessor {
    private static final Logger logger = Logger.getLogger(Zipper.class);
    private ExportJob job=null;

    public Zipper() {
        super();
    }

    public void setConfigData(Object data) {
        this.job=(ExportJob)data;
    }

    public void postProcess() throws Exception {
        if(job==null) throw new Exception("Job is null !");
        File generatedFile = new File(job.getGeneratedFileName());
        File directory = generatedFile.getParentFile();
        final String fileName = generatedFile.getName().concat(".zip");
        File zipFile = new File(directory,fileName);
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
        File[] files = directory.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return !name.equals(fileName);
            }
        });
        zos.setLevel(9);
        for(File f:files) {
            if(!f.isDirectory()) {
                ZipEntry ze = new ZipEntry(f.getName());
                zos.putNextEntry(ze);
                byte[] buffer = new byte[1024*8];
                FileInputStream fis = new FileInputStream(f);
                int read = 0;
                while((read=fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, read);
                }
                fis.close();
                zos.closeEntry();
            }
        }
        zos.close();
//        zos.finish();
        Connection con = null;
        try {
            con = PoolManager.getInstance().getConnection();
            String sql = "UPDATE EXPORT_JOBS SET GENERATED_FILE_NAME=? WHERE EXPORT_ID=?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1,zipFile.getAbsolutePath());
            ps.setLong(2,job.getIdExport());
            ps.executeUpdate();
            job.setGeneratedFileName(zipFile.getAbsolutePath());
            for(File f:files) f.delete();
        } catch(SQLException sqlEx) {
            logger.error("while changing name generated file",sqlEx);
        } finally {
            if(con!=null) PoolManager.getInstance().releaseConnection(con);
        }
    }
}
