/*
 * Copyright
 *   2009 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 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.patch.gdcombes;

import fr.gouv.finances.dgfip.xemelios.common.Scramble;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.w3c.dom.Document;

/**
 *
 * @author chm
 */
public class PatchDB {
    private static Logger logger = null;

    private static String LOG4J_BUFFER = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"+
"<log4j:configuration threshold=\"all\" debug=\"false\" xmlns:log4j=\"http://jakarta.apache.org/log4j\">\n"+
"    <appender name=\"rollingFile\" class=\"org.apache.log4j.RollingFileAppender\">\n"+
"       <param name=\"File\" value=\"patch-gdcombes.log\" />\n"+
"       <param name=\"MaxFileSize\" value=\"500KB\"/>\n"+
"       <param name=\"MaxBackupIndex\" value=\"5\"/>\n"+
"       <layout class=\"org.apache.log4j.PatternLayout\">\n"+
"           <param name=\"ConversionPattern\" value=\"%-5p [%c] %t %d{HH:mm:ss,SSS}: %m%n\"/>\n"+
"       </layout>\n"+
"   </appender>\n"+
"    <logger name=\"fr.gouv.finances\">\n"+
"        <level value=\"debug\"/>\n"+
"        <appender-ref ref=\"rollingFile\"/>\n"+
"    </logger>\n"+
"</log4j:configuration>";
    
    public PatchDB() {
        super();
    }
    public void run() {
        Connection con = null;
        try {
            File f = new File("mysql.properties");
            Properties props = new Properties();
            props.load(new FileInputStream(f));
            con = getConnection(props);
            applyPatch(con);
        } catch(Exception ex) {
            logger.error("PatchDB.run()", ex);
        } finally {
            if(con!=null) {
                try {
                    con.close();
                    con = null;
                } catch(Exception ex) {
                    logger.error("con.close()", ex);
                }
            }
        }
    }

    protected void applyPatch(Connection con) {
        sql(con,"ALTER TABLE PAYE_ETATPAYE_INDEX_PAYE ADD MT_NETAPAYER DECIMAL(14,2)","PAYE_ETATPAYE_INDEX_PAYE.MT_NETAPAYER");
        sql(con,"ALTER TABLE PAYE_ETATPAYE_INDEX_PAYE ADD PRIMARY_KEY VARCHAR(100) NOT NULL","PAYE_ETATPAYE_INDEX_PAYE.PRIMARY_KEY");
        sql(con,"ALTER TABLE PAYE_ETATPAYE_INDEX_PAYE ADD ETABL VARCHAR(100)","PAYE_ETATPAYE_INDEX_PAYE.ETABL");
        sql(con,"ALTER TABLE PAYE_NATURES_INDEX ADD MT DECIMAL(14,2)","PAYE_NATURES_INDEX.MT");
        sql(con,"ALTER TABLE PAYE_REPOSITORY ADD ID VARCHAR(25)","PAYE_REPOSITORY.ID");
        sql(con,"ALTER TABLE PAYE_REPOSITORY ADD LIBELLE VARCHAR(100)","PAYE_REPOSITORY.LIBELLE");
    }
    private void sql(Connection con, String sql, String msg) {
        try {
            con.createStatement().execute(sql);
        } catch(SQLException sqlEx) {
            logger.error(msg,sqlEx);
        }
    }

    protected Connection getConnection(Properties props) throws Exception {
        Connection ret = null;
        Class clazz = Class.forName(props.getProperty("driver.class"));
        ret = DriverManager.getConnection(
                props.getProperty("database.url"),
                props.getProperty("user"),
                Scramble.unScramblePassword(props.getProperty("password")));
        return ret;
    }

    public static void main(String args[]) {
        try {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setValidating(false);
            domFactory.setNamespaceAware(true);
            DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
            Document dom = domBuilder.parse(new ByteArrayInputStream(LOG4J_BUFFER.getBytes("UTF-8")));
            DOMConfigurator.configure(dom.getDocumentElement());
            logger = Logger.getLogger(PatchDB.class);
        } catch(Exception ex) {
            ex.printStackTrace();
        }
        new PatchDB().run();
    }

}
