/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2008 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.cp.xemelios.patch_db_delete;

import fr.gouv.finances.dgfip.xemelios.common.Constants;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
import fr.gouv.finances.dgfip.xemelios.data.DataImpl;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.cp.xemelios.data.impl.MySqlDataLayer;
import fr.gouv.finances.dgfip.xemelios.data.impl.sqlconfig.TDocument;
import fr.gouv.finances.dgfip.xemelios.data.impl.sqlconfig.TEtat;
import fr.gouv.finances.dgfip.xemelios.data.impl.sqlconfig.TPersistenceConfig;
import fr.gouv.finances.dgfip.xemelios.data.impl.sqlconfig.TTable;
import fr.gouv.finances.dgfip.xemelios.data.ui.PatchProgress;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

/**
 *
 * @author chm
 */
public class PatchRemoveFichierImpl  {
    public static final transient String PARAM_PATCH_REMOVE_FICHIER = "removeFichier.patch.applied";
    private static Logger logger = null;
    private MySqlDataLayer impl = null;
    private boolean doNotRun = false;

    public PatchRemoveFichierImpl() {
        super();
        DOMConfigurator.configure(System.getProperty("xemelios.log4j.xml"));
        logger = Logger.getLogger(PatchRemoveFichierImpl.class);
        logger.debug("instanciating");
        DataImpl di = null;
        try {
            Loader.getDocumentsInfos(System.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
            Class.forName("fr.gouv.finances.cp.xemelios.data.impl.MySqlDataLayer");
            DataLayerManager.setDataImpl("mysql");
            di = DataLayerManager.getImplementation();
        } catch(Exception ex) {
            doNotRun = true;
        }
        
        this.impl=(MySqlDataLayer)di;
        
        run();
    }
    public void run()  {
        logger.debug("run");
        if(doNotRun) return;
        String paramValue = impl.getParameterValue(PARAM_PATCH_REMOVE_FICHIER);
        if(paramValue==null) {
            Connection con = null;
            PatchProgress progress = null;
            try {
                progress = impl.getPatchProgress();
                con = impl.getConnection();
                DocumentsModel docs = null;
                try {
                    docs = Loader.getDocumentsInfos(System.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
                } catch(Exception ex) {
                    logger.error("while loading configs",ex);
                    return;
                }
                progress.setMaxProgress(docs.getDocuments().size());
                progress.startProgress("Mise à jour de votre base de données");
                for(DocumentModel dm:docs.getDocuments()) {
                    TPersistenceConfig td = impl.getPersistenceConfig(dm,(XemeliosUser)null);
                    patchConfiguration(dm,td,con);
                    progress.pushProgress();
                }
            } catch(SQLException sqlEx) {
                logger.error("run()",sqlEx);
            } catch(DataConfigurationException dcEx) {
                logger.error("run()",dcEx);
            } finally {
                if(con!=null) impl.releaseConnection(con);
                impl.killPatchProgress();
            }
            impl.setParameterValue(PARAM_PATCH_REMOVE_FICHIER, "applied");
        }
    }
    protected void patchConfiguration(DocumentModel dm,TPersistenceConfig persist,Connection con) throws SQLException {
        TDocument doc = persist.getLayer("mysql").getDocument(dm.getId());
        for(TEtat etat:doc.getEtats()) {
            for(TTable table:etat.getIndexTables()) {
                StringBuffer sb = new StringBuffer();

                sb.append("DELETE FROM ").append(table.getBaseName()).append(" USING ").append(table.getBaseName()).append(" LEFT OUTER JOIN ").append(etat.getDocumentTable().getBaseName());
                sb.append(" ON ").append(table.getBaseName()).append(".DOC_ID=").append(etat.getDocumentTable().getBaseName()).append(".DOC_ID WHERE ").append(etat.getDocumentTable().getBaseName()).append(".DOC_ID IS NULL");
System.out.println(sb.toString());
                Statement st = con.createStatement();
                st.executeUpdate(sb.toString());
                st.close();
            }
        }
    }

}
