/*
 * 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.auth;

import fr.gouv.finances.cp.utils.PropertiesExpansion;
import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.DlgConfigAuthentication;
import fr.gouv.finances.dgfip.xemelios.common.Constants;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * Permet de configurer l'authentification
 * @author chm
 */
public class CfgAuth {
    private static final Class[] parameters = new Class[] { URL.class };

    public static void main(String args[]) {
        try {
            File localDir = new File(System.getProperty("user.dir"));
            // chargement des jars pour reconstituer le classpath
            File[] jars = localDir.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    return pathname.getName().toLowerCase().endsWith(".jar") && !"auth-std-db.jar".equals(pathname.getName());
                }
            });
            for(File f:jars) addFile(f);

            // dans le cas du swing, il y a des jars dans le repertoire parent
            jars = localDir.getParentFile().listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    return pathname.getName().toLowerCase().endsWith(".jar") && !"auth-std-db.jar".equals(pathname.getName());
                }
            });
            for(File f:jars) addFile(f);

            StringBuffer notFoundLocations = new StringBuffer();
            File propertyFile = new File(localDir.getParentFile(),"mysql.properties");
            if(!propertyFile.exists()) {
                notFoundLocations.append(propertyFile.getAbsolutePath()).append(",");
                // dans le cas du batch web, il peut être dans ../conf/mysql.properties
                propertyFile = new File(new File(localDir.getParentFile(),"conf"),"mysql.properties");
            }
            if(!propertyFile.exists()) {
                notFoundLocations.append(propertyFile.getAbsolutePath()).append(",");
                notFoundLocations.deleteCharAt(notFoundLocations.length()-1);
                throw new RuntimeException("Can not find mysql.properties in ("+notFoundLocations.toString()+")");
            }
//            File xemeliosProperties = new File(localDir.getParent(),"xemelios.properties");
//            if(!xemeliosProperties.exists()) throw new RuntimeException("Can not find "+xemeliosProperties.getAbsolutePath());
            Properties props = new Properties();
//            Properties xemProps = new PropertiesExpansion();
            Connection con = null;
            try {
                props.load(new FileInputStream(propertyFile));
//                System.out.println(props);
//                xemProps.load(new FileInputStream(xemeliosProperties));
//                System.out.println(xemProps);
                PoolManager.getInstance().init(props);
                Class.forName("fr.gouv.finances.cp.xemelios.data.impl.MySqlDataLayer");
//                DataLayerManager.setDataImpl(xemProps.getProperty(Constants.SYS_PROP_DATA_IMPL));
                con = PoolManager.getInstance().getConnection();
                ResultSet rs = con.createStatement().executeQuery("SELECT PARAM_VALUE FROM PARAMETERS WHERE PARAM_NAME='authEngineClassName'");
                String initialEngineName = null;
                if(rs.next()) {
                    initialEngineName = rs.getString(1);
                    System.out.println("Current authentication engine is "+initialEngineName);
                } else
                    System.out.println("unable to read authentiation engine");
                DlgConfigAuthentication dlg = new DlgConfigAuthentication(null, true,initialEngineName);
                dlg.run();
                dlg.dispose();
                rs = con.createStatement().executeQuery("SELECT PARAM_VALUE FROM PARAMETERS WHERE PARAM_NAME='authEngineClassName'");
                if(rs.next()) {
                    System.out.println("Current authentication engine is now "+rs.getString(1));
                } else
                    System.out.println("unable to read authentiation engine");
            } catch(Exception ex) {
                throw new RuntimeException(ex);
            } finally {
                if(con!=null) PoolManager.getInstance().releaseConnection(con);
//                PoolManager.getInstance().shutdown();
            }
        } catch(Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }
    public static void addFile(File f) throws IOException {
        addURL(f.toURL());
    }

    // bitonio trouvé sur le net
    public static void addURL(URL u) throws IOException {
//System.out.println("adding to classpath "+u.toExternalForm());
        URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
        Class sysclass = URLClassLoader.class;

        try {
            Method method = sysclass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true); // voyou
            method.invoke(sysloader, new Object[] { u });
        } catch (Throwable t) {
            t.printStackTrace();
            throw new IOException("Error, could not add URL to system classloader");
        }

    }

}
