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

import fr.gouv.finances.dgfip.xemelios.batch.Batch;
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 java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import org.apache.log4j.Logger;

/**
 *
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class ExportCleaner extends Batch {
    private static final Logger logger = Logger.getLogger(ExportCleaner.class);

    public static final String PROP_MAX_CONCURRENT_THREADS = "max.concurrent.threads";
    public static final String PROP_CLEAN_DELAY = "clean.delay";
    private int maxConcurrentThreads = 1;
    private int cleanDelay = 14;

    public ExportCleaner(String[] args) {
        super(args);
    }

    @Override
    protected void initialize() throws Exception {
        super.initialize();
        String sTmp = getProps().getProperty(PROP_MAX_CONCURRENT_THREADS);
        if(sTmp!=null && sTmp.length()>0) {
            try {
                maxConcurrentThreads = Integer.parseInt(sTmp);
            } catch(Throwable t) {}
        }
        sTmp = getProps().getProperty(PROP_CLEAN_DELAY);
        if(sTmp!=null && sTmp.length()>0) {
            try {
                cleanDelay = Integer.parseInt(sTmp);
            } catch(Throwable t) {}
        }
    }

    @Override
    protected void doProcess() throws Exception {
        Connection con = null;
        try {
            con = PoolManager.getInstance().getConnection();
            StringBuffer sql = new StringBuffer("SELECT EXPORT_ID FROM EXPORT_JOBS WHERE STATUS IN (");
            sql.append(ExportJob.STATUS_DOWNLOADED).append(",").append(ExportJob.STATUS_ERROR).append(",").append(ExportJob.STATUS_TERMINATED);
            sql.append(") AND TO_DAYS(NOW()) - TO_DAYS(SUBMIT_DATE) > ").append(cleanDelay).append(" AND CLEANED IS NULL");
            ResultSet rs = con.createStatement().executeQuery(sql.toString());
            ArrayList<ExportCleanerImpl> threads = new ArrayList<ExportCleanerImpl>();
            while(rs.next()) {
                long exportId = rs.getLong(1);
                threads.add(new ExportCleanerImpl(exportId));
            }
            ThreadPool<ExportCleanerImpl> pool = new ThreadPool<ExportCleanerImpl>(threads);
            pool.start(maxConcurrentThreads);
        } catch(Exception ex) {
            logger.error("doProcess(): ",ex);
        } finally {
            if(con!=null) {
                PoolManager.getInstance().releaseConnection(con);
            }
        }
    }

    @Override
    public String getResumeTraitement() {
        return "export.cleaner.resume";
    }

    @Override
    public String typeTraitementRefCode() {
        return "export.cleaner";
    }

    protected class ExportCleanerImpl extends RunnableBatch {
        private Long exportId;

        public ExportCleanerImpl(Long exportId) {
            super();
            this.exportId=exportId;
        }

        @Override
        public void run() {
            Connection con = null;
            try {
                con = PoolManager.getInstance().getConnection();
                PreparedStatement ps = con.prepareStatement("SELECT GENERATED_FILE_NAME FROM EXPORT_JOBS WHERE EXPORT_ID=?");
                ps.setLong(1,exportId);
                ResultSet rs= ps.executeQuery();
                if(rs.next()) {
                    String generatedFileName = rs.getString(1);
                    if(rs.wasNull()) generatedFileName = null;
                    clean(generatedFileName);
                    ps = con.prepareStatement("UPDATE EXPORT_JOBS SET CLEANED=1 WHERE EXPORT_ID=?");
                    ps.setLong(1,exportId);
                    ps.executeUpdate();
                }
            } catch(Exception ex) {
                logger.error("ExportCleanerImpl.run(): ",ex);
            } finally {
                if(con!=null) {
                    PoolManager.getInstance().releaseConnection(con);
                }
            }
        }
        protected void clean(String fileName) {
            if(fileName==null) return;
            File f = new File(fileName);
            if(f.exists()) {
                File dir = f.getParentFile();
                try {
                    FileUtils.dropRecursiveDirectory(dir);
                } catch(Exception ex) {}
            }
        }

    }

}
