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

import fr.gouv.finances.dgfip.xemelios.batch.Batch;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import org.apache.log4j.Logger;

/**
 *
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class ExportEvaluator extends Batch {
    private static final Logger logger = Logger.getLogger(ExportEvaluator.class);
    private static final int EXPORT_MAX_SIZE = 1000;
    private static final int EXPORT_P1_MAX_SIZE = 10;
    private static final int EXPORT_P2_MAX_SIZE = 100;
    public static final int MAX_CONCURRENT_THREADS = 3;

    public static final String PROP_EXP_MAX_SIZE = "export.max.size";
    public static final String PROP_P1_MAX_SIZE = "export.p1.max.size";
    public static final String PROP_P2_MAX_SIZE = "export.p2.max.size";
    public static final String PROP_MAX_CONCURRENT_THREADS = "max.concurrent.threads";

    private int maxConcurrentThreads = MAX_CONCURRENT_THREADS;
    private int p1MaxSize = EXPORT_P1_MAX_SIZE;
    private int p2MaxSize = EXPORT_P2_MAX_SIZE;
    private int maxSize = EXPORT_MAX_SIZE;

    private ThreadPool<ExportEvaluatorImpl> pool=null;

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

    @Override
    protected void initialize() throws Exception {
        super.initialize();
        try {
            String s = getProps().getProperty(PROP_EXP_MAX_SIZE);
            if(s!=null && s.length()>0) {
                maxSize = Integer.parseInt(s);
            }
        } catch(Throwable t) {}
        try {
            String s = getProps().getProperty(PROP_P1_MAX_SIZE);
            if(s!=null && s.length()>0) {
                p1MaxSize = Integer.parseInt(s);
            }
        } catch(Throwable t) {}
        try {
            String s = getProps().getProperty(PROP_P2_MAX_SIZE);
            if(s!=null && s.length()>0) {
                p2MaxSize = Integer.parseInt(s);
            }
        } catch(Throwable t) {}
        String sTmp = getProps().getProperty(PROP_MAX_CONCURRENT_THREADS);
        if(sTmp!=null && sTmp.length()>0) {
            try {
                maxConcurrentThreads = Integer.parseInt(sTmp);
            } catch(Throwable t) {}
        }
    }



    @Override
    protected void doProcess() throws Exception {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        ArrayList<ExportEvaluatorImpl> threads = new ArrayList<ExportEvaluatorImpl>();
        try {
            con = PoolManager.getInstance().getConnection();
            String sqlParam = "SELECT PARAM_VALUE FROM PARAMETERS WHERE PARAM_NAME='export.temp.directory'";
            st = con.createStatement();
            rs = st.executeQuery(sqlParam);
            if(rs.next()) {
                String exportTempDirectory = rs.getString(1);
                rs.close();
            } else {
                logger.error("parameter 'export.temp.directory' not set !");
                throw new Exception("parameter 'export.temp.directory' not set !");
            }
            String sql = "SELECT EXPORT_ID FROM EXPORT_JOBS WHERE STATUS=0";
            rs = st.executeQuery(sql);
            while(rs.next()) {
                threads.add(new ExportEvaluatorImpl(rs.getLong(1),p1MaxSize,p2MaxSize,maxSize));
            }
            pool = new ThreadPool<ExportEvaluatorImpl>(threads);
            pool.start(maxConcurrentThreads);
        } catch(SQLException sqlEx) {
            // TODO
        } finally {
            if(con!=null) PoolManager.getInstance().releaseConnection(con);
        }
    }

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

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

    @Override
    public String getInformations() {
        StringBuilder sb = new StringBuilder();
        if(isStarted()) {
            sb.append(typeTraitementRefCode()).append(" - ").append(pool.getRunningThreadCount()).append(" running thread(s)\n");
            for(RunnableBatch rb: pool.getThreads()) {
                sb.append("\t").append(rb.getName()).append(": ").append(rb.isAlive()?"running":"idle").append("\n");
                if(rb.isAlive()) sb.append(rb.getInformations());
            }
        } else {
            sb.append(typeTraitementRefCode()).append(" - not started\n");
        }
        return sb.toString();
    }

    protected class ExportEvaluatorImpl extends RunnableBatch {
        private final Logger logger = Logger.getLogger(ExportEvaluatorImpl.class);
        private Long exportId;
        private int p1MaxSize, p2MaxSize, maxSize;
        public ExportEvaluatorImpl(Long exportId,int p1MaxSize, int p2MaxSize, int maxSize) {
            this.exportId=exportId;
            this.p1MaxSize=p1MaxSize;
            this.p2MaxSize=p2MaxSize;
            this.maxSize=maxSize;
            setName("ExportEvaluatorImpl<"+exportId+">");
        }

        @Override
        @SuppressWarnings("unchecked")
        public void run() {
            Connection con = null;
            try {
                int priority = -1;
                String errorMessage=null;
                con = PoolManager.getInstance().getConnection();
                PreparedStatement ps = con.prepareStatement("SELECT SIZE FROM EXPORT_JOBS WHERE EXPORT_ID=?");
                ps.setLong(1,exportId);
                ResultSet rs = ps.executeQuery();
                if(rs.next()) {
                    int size = rs.getInt(1);
                    if(size<p1MaxSize) priority = 1;
                    else if(size<p2MaxSize) priority = 2;
                    else if(size<maxSize) priority = 3;
                    else errorMessage="Il y a trop de données à exporter pour réaliser cet export.";
                } else {
                    errorMessage = "Erreur inattendue";
                }
                if(priority>0) {
                    ps = con.prepareStatement("UPDATE EXPORT_JOBS SET PRIORITY=?, STATUS=1 WHERE EXPORT_ID=?");
                    ps.setInt(1,priority);
                    ps.setLong(2,exportId);
                    ps.executeUpdate();
                } else {
                    ps = con.prepareStatement("UPDATE EXPORT_JOBS SET ERROR_MESSAGE=? ,STATUS=5 WHERE EXPORT_ID=?");
                    ps.setString(1,errorMessage);
                    ps.setLong(2, exportId);
                    ps.executeUpdate();
                }
            } catch(SQLException sqlEx) {
                logger.error("run<"+exportId+">()", sqlEx);
            } finally {
                if(con!=null) PoolManager.getInstance().releaseConnection(con);
                getNotifier().notifyThreadStop(this);
            }
        }

        @Override
        public String getInformations() {
            return "\tevaluating export :".concat(Long.toString(exportId)).concat("\n");
        }
    }


}
