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

import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.JdbcUtils;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.PStmtBinder;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.RowMapper;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;

/**
 * This class provides utility method for web imports
 * @author chm
 */
public class ImportHelper {
    private static final Logger logger = Logger.getLogger(ImportHelper.class);
    public static final int IMPORT_STATUS_PENDING = 0;
    public static final int IMPORT_STATUS_ANALYSE = 1;
    public static final int IMPORT_STATUS_PRECISE = 2;
    public static final int IMPORT_STATUS_RUNNING = 3;
    public static final int IMPORT_STATUS_SUCCESS = 4;
    public static final int IMPORT_STATUS_ERROR   = 5;
    public static final int IMPORT_STATUS_WAIT_FOR_IMPORT = 6;
    public static final String[] IMPORT_STATUS_LIB = { "En attente d'analyse", "Analyse en cours", "Pr&eacute;cisions requises", "En cours", "Termin&eacute;", "Erreur", "En attente d'import" };

    private static File importDirectory = null;

    public static List<Import> get7daysImports(XemeliosUser user) {
        List<Import> ret = new ArrayList<Import>();
        StringBuffer sb = new StringBuffer(Import.SELECT);
        sb.append(" WHERE UTI_LOGIN=? AND (STATUS IN (0,1,2,3,6) OR DATE_SUB(CURDATE(),INTERVAL 7 DAY) < END_DATE)");
        Connection con = null;
        try {
            con = PoolManager.getInstance().getConnection();
            ret = JdbcUtils.queryObjects(con, sb.toString(), new RowMapper() {
                public Object map(ResultSet arg0) throws SQLException {
                    return new Import(arg0);
                }
            }, new PStmtBinder.SimplePStmtBinderBuilder().add(user.getId()).toPStmtBinder());
        } catch(SQLException sqlEx) {
            logger.error("getImports(XemeliosUser)",sqlEx);
        } finally {
            if(con!=null) PoolManager.getInstance().releaseConnection(con);
        }
        return ret;
    }

    public static Import newImport(XemeliosUser user, File file, String fileName, String fileType, String ipAddress) {
        Import ip = new Import();
        ip.setUserLogin(user.getId());
        ip.setStatus(IMPORT_STATUS_PENDING);
        ip.setSubmitDate(System.currentTimeMillis());
        ip.setImportId(ipAddress.concat("-").concat(Long.toString(ip.getSubmitDate().getTime())));
        ip.setFileName(fileName);
        ip.setFileType(fileType);
        Connection con = null;
        try {
            con = PoolManager.getInstance().getConnection();
            String sql="INSERT INTO XEM_IMPORTS(UTI_LOGIN,IMPORT_ID,FILE_NAME,FILE_TYPE,SUBMIT_DATE,STATUS) VALUES (?,?,?,?,?,?)";
            JdbcUtils.executeUpdate(con, sql,new PStmtBinder.SimplePStmtBinderBuilder().add(ip.getUserLogin()).add(ip.getImportId()).add(ip.getFileName()).add(ip.getFileType()).add(ip.getSubmitDate()).add(ip.getStatus()).toPStmtBinder());
        } catch(SQLException sqlEx) {
            logger.error("newImport(XemeliosUser,File,String,String)",sqlEx);
            return null;
        } finally {
            if(con!=null) PoolManager.getInstance().releaseConnection(con);
        }
        File importDir = new File(getImportDirectory(),ip.getImportId());
        importDir.mkdirs();
        File destFile = new File(importDir,ip.getFileName());
        file.renameTo(destFile);
        return ip;
    }

    public static File getImportDirectory() {
        if(importDirectory==null) {
            try {
                String sDir = DataLayerManager.getImplementation().getParameterValue("import.directory");
                if(sDir!=null) {
                    File f = new File(sDir);
                    if(!f.exists()) {
                        f.mkdirs();
                    }
                    importDirectory = f;
                } else {
                    throw new RuntimeException("import.directory parameter is not set !");
                }
            } catch(Exception ex) {
                logger.error("getImportDirectory()",ex);
            }
        }
        return importDirectory;
    }

    public static Import getImport(XemeliosUser user, String importId) {
        Import ret = null;
        Connection con = null;
        StringBuffer importSb = new StringBuffer(Import.SELECT);
        importSb.append(" WHERE UTI_LOGIN=? AND IMPORT_ID=?");

        StringBuffer importFileSb = new StringBuffer(ImportFile.SELECT);
        importFileSb.append(" WHERE IMPORT_ID=?");
        try {
            con = PoolManager.getInstance().getConnection();
            ret = (Import)JdbcUtils.queryObject(con, importSb.toString(), new RowMapper() {
                public Object map(ResultSet arg0) throws SQLException {
                    return new Import(arg0);
                }
            }, new PStmtBinder.SimplePStmtBinderBuilder().add(user.getId()).add(importId).toPStmtBinder());
            if(ret!=null) {
                @SuppressWarnings("unchecked")
                List<ImportFile> files = (List<ImportFile>)JdbcUtils.queryObjects(con, importFileSb.toString(), new RowMapper() {

                    public Object map(ResultSet arg0) throws SQLException {
                        return new ImportFile(arg0);
                    }
                }, new PStmtBinder.SimplePStmtBinderBuilder().add(importId).toPStmtBinder());
                ret.setImportFiles(files);
            }
        } catch(SQLException sqlEx) {
            logger.error("getImports(XemeliosUser)",sqlEx);
        } finally {
            if(con!=null) PoolManager.getInstance().releaseConnection(con);
        }
        return ret;
    }

}
