/*
 * Copyright
 *   2009 axYus - www.axyus.com
 *   2009 C.Bosquet - charles.bosquet@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.xemelios.batch;

import fr.gouv.finances.dgfip.utils.DateUtils;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

/**
 * @author CBO
 */
public abstract class AbstractBatch {

    static private final int SUCCESS_RETURN_CODE = 0;
    static private final int ERROR_RETURN_CODE = 1;
    private String args[];
    private Logger logger;
    private Date startDate;
    private String batchVersion;
    private SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

    abstract protected void process() throws Exception;

    public AbstractBatch(String args[]) {
        this.args = args;
    }

    protected boolean canStart() throws Exception {
        return true;
    }

    protected void processTerminaison() throws Exception {
    }

    public String[] getArgs() {
        return args;
    }

    public int launchBatch() {
        int codeRetour = ERROR_RETURN_CODE;
        try {
//            // On initialise dans un premier temps les logs :
//            File log4jConfiFile = getConfFile("log4j.conf.file", "log4j.xml");
//            if (log4jConfiFile == null) {
//                throw new Exception("Fichier de configuration de log4j introuvable");
//            }
//            DOMConfigurator.configure(log4jConfiFile.toString());
            this.logger = Logger.getLogger(this.getClass());
            // On initialise le reste :
            initialize();
            if (canStart()) {
                try {
                    this.startDate = new Date();
                    getLogger().info("Début du traitement de " + getShortName() + " " + getBatchVersion() + " le " + DateUtils.formatDateTime(startDate));
                    getLogger().info("Max memory : " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " Mb");
                    getLogger().info("Total free memory : " + ((Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) / 1024 / 1024) + " Mb");
                    process();
                    Date endDate = new Date();
                    long duration = endDate.getTime() - startDate.getTime();
                    getLogger().info("Fin du traitement de " + getShortName() + " " + getBatchVersion() + " le " + DateUtils.formatDateTime(endDate) + " , durée : " + DateUtils.durationToString(duration));
                } finally {
                    processTerminaison();
                }
            }
            codeRetour = SUCCESS_RETURN_CODE;
        } catch (Throwable throwable) {
            String errorMessage = throwable.getMessage() != null ? throwable.getMessage() : throwable.toString();
            if (this.logger != null) {
                getLogger().error(errorMessage, throwable);
            }
            System.err.println("ERROR : " + DateUtils.formatDateTime(new Date()) + " : " + errorMessage);
            throwable.printStackTrace();
        }
        return codeRetour;
    }

    protected void initialize() throws Exception {
        File poolConfigFile = getConfFile("pool.conf.file", "mysql.properties");
        if (poolConfigFile == null) {
            throw new Exception("Fichier de configuration d'accès à la base de données non paramétré");
        }
        if (!poolConfigFile.exists()) {
            throw new Exception("Fichier de configuration d'accès à la base de données introuvabel: " + poolConfigFile.getAbsolutePath());
        }
        Properties props = new Properties();
        props.load(new FileInputStream(poolConfigFile));
        PoolManager.getInstance().init(props);
        Properties pomProperties = new Properties();
        this.batchVersion = "unknown";
    }

    protected Logger getLogger() {
        if (logger == null) {
            throw new RuntimeException("Logger is not yet initialized");
        }
        return this.logger;
    }

    public Date getStartDate() {
        return startDate;
    }

    protected String getShortName() {
        return getClass().getName().substring(getClass().getName().lastIndexOf(".") + 1);
    }

    protected String getBatchVersion() {
        return this.batchVersion;
    }

    protected File getConfFile(String fileNameSystemProperty, String fileNameIfSystemPropertyNotFound) {
        return getConfFile(fileNameSystemProperty, fileNameIfSystemPropertyNotFound, fileNameIfSystemPropertyNotFound);
    }

    protected File getConfFile(String fileNameSystemProperty, String fileNameIfSystemPropertyNotFound, String errorDisplayName) {
        String confFileName = System.getProperty(fileNameSystemProperty);
        File confFile = null;
        if (confFileName == null) {
            confFileName = "conf" + File.separator + fileNameIfSystemPropertyNotFound;
            confFile = new File(confFileName);
            if (!confFile.exists()) {
                confFileName = fileNameIfSystemPropertyNotFound;
                confFile = new File(confFileName);
                if (!confFile.exists()) {
                    return null;
                }
            }
        } else {
            confFile = new File(confFileName);
            if (!confFile.exists()) {
                return null;
            }
        }
        return confFile;
    }
}
