 /*
 * Copyright 
 *   2008 axYus - www.axyus.com
 *   2008 jp.tessier - jean-philippe.tessier@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.cp.xemelios.plugin.generatorEdmn;

import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import java.io.File;
import java.io.FilenameFilter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
import fr.gouv.finances.cp.xemelios.data.impl.MySqlDataLayer;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter;
import java.lang.reflect.Constructor;

/**
 *
 * @author chm
 */
public class EdmnImporter extends DefaultImporter {

    private static final Logger logger = Logger.getLogger(EdmnImporter.class);
    private static final String TABLE_INDEX = EdmnImporteurWorker.TABLE_INDEX;
    
    private static final String TABLE_BUDGETS = EdmnImporteurWorker.TABLE_BUDGETS;
    private static final String TABLE_ORDOS = EdmnImporteurWorker.TABLE_ORDOS;
    private static final String TABLE_COMPTABLES = EdmnImporteurWorker.TABLE_COMPTABLES;

    private static final String SCRIPT_BUDGET = "CREATE TEMPORARY TABLE IF NOT EXISTS "+TABLE_BUDGETS+" (\n"+
        "BUD_ANNEE VARCHAR(4) not null,\n"+
        "BUD_TYPE_ENREGISTREMENT VARCHAR(2) not null,\n"+
        "BUD_MINISTERE VARCHAR(2) not null,\n"+
        "BUD_PROGRAMME VARCHAR(4) not null,\n"+
        "BUD_ACTION VARCHAR(2) not null,\n"+
        "BUD_ARTICLE VARCHAR(2) not null,\n"+
        "BUD_LIBELLE VARCHAR(500)\n"+
    ")";
    private static final String SCRIPT_ORDOS = "CREATE TEMPORARY TABLE IF NOT EXISTS "+TABLE_ORDOS+" (\n"+
        "ORD_CODE VARCHAR(3) not null,\n"+
        "ORD_COMPTE VARCHAR(5),\n"+
        "ORD_SECTION VARCHAR(2),\n"+
        "ORD_LIBELLE VARCHAR(500),\n"+
        "ORD_TRIMESTRE VARCHAR(1) not null,\n"+
        "ORD_ANNEE VARCHAR(4) not null\n"+
    ")";
    private static final String SCRIPTS_COMPTABLES = "CREATE TEMPORARY TABLE IF NOT EXISTS "+TABLE_COMPTABLES+" (\n"+
        "CMP_CODE VARCHAR(6) not null,\n"+
        "CMP_LIBELLE VARCHAR(75),\n"+
        "CMP_TRIMESTRE VARCHAR(1) not null,\n"+
        "CMP_ANNEE VARCHAR(4) not null\n"+
    ")";
    private static final String SCRIPT_INDEX = "CREATE TEMPORARY TABLE IF NOT EXISTS "+TABLE_INDEX+" (\n"+
        "IND_ANNEE VARCHAR(4) not null,\n"+
        "IND_TRIMESTRE VARCHAR(1) not null,\n"+
        "IND_COMPTABLE VARCHAR(6) not null,\n"+
        "IND_MINISTERE VARCHAR(3) not null,\n"+
        "IND_LOCALE VARCHAR(4) not null,\n"+
        "IND_GESTION VARCHAR(3),\n"+
        "IND_SECTION VARCHAR(3),\n"+
        "IND_NATIONALE VARCHAR(6)\n"+
    ")";
    // Variables de progression d'avancement de la progrsse barre
    private static ProgressFrame progress;
    private DlgGenEdmn dlg;

    public EdmnImporter() {
        super(new XemeliosUser() {

            public String getId() {
                return "edmn importer user";
            }

            public String getDisplayName() {
                return getId();
            }

            public boolean hasRole(String role) {
                return true;
            }

            public boolean hasDocument(String document) {
                return true;
            }

            public boolean hasCollectivite(String collectivite, DocumentModel dm) {
                return true;
            }
        });
    }

    public EdmnImporter(DlgGenEdmn dlg) {
        this();
        this.dlg = dlg;
    }

    /**
     * @author jp.tessier
     * @param f : file EDMN
     * @param index : index of correspondance NumLiasseLocale <=> NumLiasseNationnale
     * @throws Exception
     */
    public void importFile(File f, File index, File budgets, File ordos,File comptas,File output) throws Exception {
        Connection con = null;
        try {
//            MySqlDataLayer msdl = (MySqlDataLayer) DataLayerManager.getImplementation();
            con = PoolManager.getInstance().getConnection();
            createDataBase(con);
            createDataBaseBudgets(con);
            createDataBaseOrdos(con);
            createDataBaseComptables(con);

            EdmnImporteurWorker eiw = new EdmnImporteurWorker(con,budgets,ordos,comptas,output,dlg);
         	
            File[] tabF = {f, index,budgets,ordos,comptas};
            progress = new ProgressFrame(dlg, eiw, tabF);
            progress.setDisplayFeedback(true);

            eiw.setProgressDlg(progress);
            eiw.setFilesToTreat(tabF);
            eiw.execute();
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("doImport", ex);
            new DisplayExceptionDlg(dlg, ex);
        } finally {
            if(progress!=null && progress.pg!=null)
                progress.pg.setVisible(false);
        }
    }
        

    private void createDataBase(Connection con) throws SQLException {
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(SCRIPT_INDEX);
            ps.execute();
            ps = con.prepareStatement("TRUNCATE TABLE " + TABLE_INDEX);
            ps.execute();
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable t) {
                }
            }
        }
    }
    
    private void createDataBaseBudgets(Connection con) throws SQLException {
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(SCRIPT_BUDGET);
            ps.execute();
            ps = con.prepareStatement("TRUNCATE TABLE " + TABLE_BUDGETS);
            ps.execute();
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable t) {
                }
            }
        }
    }
    
    private void createDataBaseOrdos(Connection con) throws SQLException {
        PreparedStatement ps = null;
        try {
            // Creation de la table si inexistente
            ps = con.prepareStatement(SCRIPT_ORDOS);
            ps.execute();
            // Vidage de la table d'index budgets
            ps = con.prepareStatement("TRUNCATE TABLE " + TABLE_ORDOS);
            ps.execute();
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable t) {
                }
            }
        }
    }
    
    private void createDataBaseComptables(Connection con) throws SQLException {
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(SCRIPTS_COMPTABLES);
            ps.execute();    
            ps = con.prepareStatement("TRUNCATE TABLE " + TABLE_COMPTABLES);
            ps.execute();        
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable t) {
                }
            }
        }
    }
}
