/*
 * 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.imports;

import fr.gouv.finances.cp.xemelios.importers.batch.BatchRealImporter;
import fr.gouv.finances.dgfip.xemelios.batch.Batch;
import fr.gouv.finances.dgfip.xemelios.batch.BatchRunner;
import fr.gouv.finances.dgfip.xemelios.batch.imports.utils.ImportVOFull;
import fr.gouv.finances.dgfip.xemelios.batch.imports.utils.ImportVOPK;
import fr.gouv.finances.dgfip.xemelios.batch.imports.utils.ImportVOWrapper;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author chm
 */
public class Importer extends Batch {
    public static final int MAX_CONCURRENT_THREADS = 3;
    private int maxConcurrentThreads = MAX_CONCURRENT_THREADS;
    private String documentsDefDirs = null;

    private String importDirectory = null;

    private ThreadPool<ImporterImpl> pool = null;

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

    @Override
    protected void initialize() throws Exception {
        super.initialize();
        String dirs = getProps().getProperty("documents-def.dir");
        File baseDir = BatchRunner.getBaseDir();
        String canon = baseDir.getCanonicalPath().replace("\\", "/");
        documentsDefDirs = dirs.replaceAll("%basedir%", canon);
        String sTmp = getProps().getProperty("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<ImporterImpl> threads = new ArrayList<ImporterImpl>();
        try {
            con = PoolManager.getInstance().getConnection();
            String sqlParam = "SELECT PARAM_VALUE FROM PARAMETERS WHERE PARAM_NAME='import.directory'";
            st = con.createStatement();
            rs = st.executeQuery(sqlParam);
            if(rs.next()) {
                importDirectory = rs.getString(1);
                rs.close();
            } else {
                throw new Exception("parameter 'import.directory' not set !");
            }
            StringBuffer select = new StringBuffer();
            String sql = "SELECT IMPORT_ID FROM XEM_IMPORTS WHERE STATUS=6";
            rs = st.executeQuery(sql);
            while(rs.next()) {
                threads.add(new ImporterImpl(rs.getString(1),importDirectory,documentsDefDirs));
            }
            PoolManager.getInstance().releaseConnection(con); con=null;
            pool = new ThreadPool<ImporterImpl>(threads);
            pool.start(maxConcurrentThreads);
        } catch(SQLException sqlEx) {
            sqlEx.printStackTrace();
        } finally {
            if(con!=null) {
                PoolManager.getInstance().releaseConnection(con);
            }
        }
    }

    @Override
    public String getResumeTraitement() {
        return "resume importer";
    }

    @Override
    public String typeTraitementRefCode() {
        return "importer";
    }

    @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();
    }

    @Override
    protected String getBatchVersion() {
        return "1.0";
    }

    private class ImporterImpl extends RunnableBatch {
        private String importId;
        private String importDirectory;
        private String confDir;

        // utilities
        ImportVOFull importFull=null;

        public ImporterImpl(String importId, String importDirectory, String confDir) {
            this.importId=importId;
            this.importDirectory=importDirectory;
            this.confDir = confDir;
            setName("ImporterImpl<".concat(importId).concat(">"));
        }

        @Override
        @SuppressWarnings("unchecked")
        public void run() {
            Connection con = null;
            try {
                con = PoolManager.getInstance().getConnection();
                loadImportInfos(con);
                importFull.setStatus(3);
                ImportVOWrapper.updateImportVO(con, importFull);
                PoolManager.getInstance().releaseConnection(con); con=null;

//                String args[] = new String[] {
//                    "-g", confDir,
//                    "-d",importFull.getFileType(),
//                    "-b",importFull.getBudget(),importFull.getBudgetLib(),
//                    "-c",importFull.getCollectivite(),importFull.getCollectiviteLib(),
//                    "-u",importFull.getUtiLogin(),
//                    "-i","no","no",
//                    "-f",new File(new File(new File(importDirectory),importFull.getImportId()),importFull.getFileName()).getAbsolutePath()
//                };

                ArrayList<String> argList = new ArrayList<String>();
                argList.add("-g");  argList.add(confDir);
                argList.add("-d");  argList.add(importFull.getFileType());
                if(importFull.getBudget()!=null && importFull.getBudgetLib()!=null) {
                    argList.add("-b");  argList.add(importFull.getBudget());    argList.add(importFull.getBudgetLib());
                }
                if(importFull.getCollectivite()!=null && importFull.getCollectiviteLib()!=null) {
                    argList.add("-c");  argList.add(importFull.getCollectivite()); importFull.getCollectiviteLib();
                }
                argList.add("-u");  argList.add(importFull.getUtiLogin());
                argList.add("-i");  argList.add("no"); argList.add("no");
                argList.add("-f");  argList.add(new File(new File(new File(importDirectory),importFull.getImportId()),importFull.getFileName()).getAbsolutePath());
                
                
                
                
//                args[i++] = "-g";
//                args[i++] = confDir;
//                args[i++] = "-d";
//                args[i++] = importFull.getFileType();
//                args[i++] = "-b";
//                args[i++] = importFull.getBudget();
//                args[i++] = importFull.getBudgetLib();
//                args[i++] = "-c";
//                args[i++] = importFull.getCollectivite();
//                args[i++] = importFull.getCollectiviteLib();
//                args[i++] = "-u";
//                args[i++] = importFull.getUtiLogin();
//                args[i++] = "-i";
//                args[i++] = "no";
//                args[i++] = "no";
//                args[i++] = "-f";
//                args[i++] = new File(new File(new File(importDirectory),importFull.getImportId()),importFull.getFileName()).getAbsolutePath();
                String[] args = new String[argList.size()];
                args = argList.toArray(args);
                BatchRealImporter.main(args);
                importFull.setStatus(4);
            } catch(Exception ex) {
                ex.printStackTrace();
                importFull.setStatus(5);
                importFull.setErrorMessage(ex.getMessage());
            } finally {
                try {
                    if(con==null) con=PoolManager.getInstance().getConnection();
                    ImportVOWrapper.updateImportVO(con, importFull);
                } catch (SQLException ex1) {
                    ex1.printStackTrace();
                }
                if(con!=null) {
                    PoolManager.getInstance().releaseConnection(con);
                }
                getNotifier().notifyThreadStop(this);
            }
        }


        public void loadImportInfos(Connection con) throws SQLException {
            ImportVOPK pk = new ImportVOPK(importId);
            importFull = ImportVOWrapper.getImportVOFullByPk(con, pk);
        }

        @Override
        public String getInformations() {
            if(isAlive()) return "\t".concat(getName()).concat(": running\n");
            else return "\t".concat(getName()).concat(": idle\n");
        }


    }

}
