/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2005 L.Meckert - lmeckert@club-internet.fr
 *
 * 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.utils;

//import edu.stanford.ejalbert.BrowserLauncher;
//import edu.stanford.ejalbert.exception.BrowserLaunchingInitializingException;
//import edu.stanford.ejalbert.exception.UnsupportedOperatingSystemException;
import fr.gouv.finances.dgfip.utils.Jnideps;
import fr.gouv.finances.dgfip.xemelios.common.Constants;
import java.lang.reflect.Method;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;

import fr.gouv.finances.dgfip.xemelios.common.ToolException;

// Recuperer le path du navigateuir dans le registre
// et visualiser une URL
//
// Exemple java StartUrl http://wwww.google.fr

public class StartUrl {
//    private static BrowserLauncher instance = null;
    public static Logger logger = Logger.getLogger(StartUrl.class);
    
    public static void startUrl(String url) throws ToolException {
        //startUrlOldFashion(url);
        launchURL(url);
        //launchBrowserLauncher2(url);
    }
    /**
     * Lance le navigateur systeme sur l'URL choisie
     *
     * Usage : try { StartUrl.startUrl(url) } catch(ToolException te){ traiter}
     */
    protected static void startUrlOldFashion(String url) throws ToolException {
        // Appelle la methode getRegistryEntry de la classe RegAccess
        String testKey = "HKEY_CLASSES_ROOT\\HTTP\\SHELL\\OPEN\\COMMAND";
        
        String strValue = System.getProperty(Constants.SYS_PROP_NAVIGATOR_CMD_LINE);
        try {
            if (strValue == null)
                strValue = Jnideps.invoke("fr.gouv.finances.cp.utils.RegAccess", "getRegistryEntry", testKey);
        } catch (ToolException e) {
            throw e;
        }
        if (strValue != null) {
        } else {
            throw new ToolException("Entree de registre " + testKey + " non trouvee", ToolException.ERROR_JNIDEPS_BADPARAMS);
        }
        String commandLine;
        
        // Avec Firefox faut remplacer %1 par l(URL
        if (strValue.indexOf("%1") > 0) {
            commandLine = strValue.replace("%1", url);
        } else // Avec IE faut ajouter l'URL a la fin
        {
            commandLine = strValue + " " + url;
        }
        try {
            logger.debug("launching " + commandLine);
            Runtime.getRuntime().exec(commandLine);
        } catch (Exception e) {
            throw new ToolException("Echec du lancement du navigateur par la commande " + commandLine, e, ToolException.ERROR_JNIDEPS_BADPARAMS);
        }
    }
    protected static void launchURL(String url){
        
        String osName = System.getProperty("os.name");
        try {
            if (osName.startsWith("Mac OS")) {
                // Mac OS X can handle file types itself (thank  goodness!)
                Class fileMgr = Class.forName("com.apple.eio.FileManager");
                Method openURL = fileMgr.getDeclaredMethod("openURL",new Class[] {String.class});
                openURL.invoke(null, new Object[] {url});
            } else if (osName.startsWith("Windows")) { // who knows  what Windows does ...
                // il y a un bug avec Windows 2000, il faut que le fichier commence par file:// au lieu de file:/
                if("Windows 2000".equals(System.getProperty("os.name")) || "Windows 98".equals(System.getProperty("os.name"))) {
                    if(url.startsWith("file:/") && !url.startsWith("file://"))
                        url = "file://"+url.substring(6);
                }
                if(url.indexOf(' ')>=0) {
                    url = "\"".concat(url).concat("\"");
                }
                if(url.toLowerCase().endsWith(".html") && System.getProperty(Constants.SYS_PROP_NAVIGATOR_CMD_LINE)!=null) {
                    Runtime.getRuntime().exec(System.getProperty(Constants.SYS_PROP_NAVIGATOR_CMD_LINE)+" \""+url+"\"");
                } else
                    Runtime.getRuntime().exec("rundll32  url.dll,FileProtocolHandler " + url);
            } else if (osName.equalsIgnoreCase("Linux") ||  osName.equalsIgnoreCase("sunos") || osName.equalsIgnoreCase("solaris")) { //  Linux, etc.
                // launch pdf files on Linux
                if(url.endsWith(".pdf") || url.endsWith(".PDF")){
                    String[] pdfViewers = {"evince", "kpdf", "xpdf", "Xpdf", "gv",  "acroread", "acrobat", "kghostview" };
                    String viewer = null;
                    // pick the PDF Viewer
                    for (int count = 0; count < pdfViewers.length &&  viewer == null; count++)
                        if (Runtime.getRuntime().exec(new String[] {"which", pdfViewers [count]}).waitFor() == 0)
                            viewer = pdfViewers[count];
                    if (viewer == null) // got no pdf viewer
                        throw new Exception("Could not find PDF  Viewer");
                    else { // got a pdf viewer, so launch it
                        int ind = url.indexOf(":");
                        if(ind >= 0){
                            url.substring(ind);
                        }
                        Runtime.getRuntime().exec(new String[]  {viewer, url});
                    }
                    // launch html urls in a browser
                } else if (url.startsWith("http") || url.endsWith("html") || url.endsWith("htm") || url.endsWith("HTML") ||  url.endsWith("HTM")){
                    String[] browsers = { // list of html browsers
                        "firefox", "opera", "konqueror", "epiphany",  "mozilla", "netscape" };
                    String browser = null;
                    for (int count = 0; count < browsers.length &&  browser == null; count++)
                        if (Runtime.getRuntime().exec(
                            new String[] {"which", browsers [count]}).waitFor() == 0)
                            browser = browsers[count];
                    if (browser == null) // got no browser, bummer
                        throw new Exception("Could not find web  browser");
                    else // got a browser, run it
                        Runtime.getRuntime().exec(new String[]  {browser, url});
                } else {
                    // try with browser
                    String[] browsers = { "firefox", "opera", "konqueror", "epiphany",  "mozilla", "netscape" };
                    String browser = null;
                    for (int count = 0; count < browsers.length &&  browser == null; count++)
                        if (Runtime.getRuntime().exec(
                            new String[] {"which", browsers [count]}).waitFor() == 0)
                            browser = browsers[count];
                    if (browser == null) // got no browser, bummer
                        throw new Exception("Could not find web  browser");
                    else // got a browser, run it
                        Runtime.getRuntime().exec(new String[]  {browser, url});
                }
            }
        } catch (Exception e) { // bollux!
            JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        }
    }
    
//    protected static void launchBrowserLauncher2(String url) {
//        try {
//            if(instance==null) {
//                instance = new BrowserLauncher();
////                instance.setNewWindowPolicy(true);
//            }
//            instance.openURLinBrowser(url);
//        } catch(BrowserLaunchingInitializingException bliEx) {
//            JOptionPane.showMessageDialog(null, bliEx.getLocalizedMessage());
//        } catch(UnsupportedOperatingSystemException uosEx) {
//            JOptionPane.showMessageDialog(null, uosEx.getLocalizedMessage());
//        }
//    }
    public static void main(String[] argv) throws ToolException {
        // Attend une URL en parametre; je teste juste s'il y a un prametre
        if (argv.length < 1) {
            System.exit(1);
        }
        
        
        startUrl(argv[0]);
        
    }
}
