/* ----------------------------------------
 * Origin  : GFI INFORMATIQUE 
 * Project : CDPP Propagation Tool 
 * ----------------------------------------
 * History 
 * Version : 01/05/2015 : SCA : V2.1
 * VERSION : V2.13
 * DM-ID : redmine#12167: 07/11/2025 : LBE : Start Desktop in Thread for Linux
 * ----------------------------------------
 */
package fr.tlse.irap.pt.client.controller.tools.common;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;

import fr.tlse.irap.pt.client.controller.dialogbox.DialogBox;

public class DesktopBrowser {

    static final String[] browsers = {"firefox", "safari", "google-chrome", "opera", "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla"};

    /**
     * Open an URL using the default browser
     *
     * @param url
     * @throws URISyntaxException
     * @throws IOException
     */
    public static void open(String url) throws Exception {
        if (Desktop.isDesktopSupported()) {
            new Thread(() -> {
                try {
                    Desktop.getDesktop().browse(new URI(url));
                } catch (IOException | URISyntaxException e) {
                    e.printStackTrace(System.err);
                }
            }).start();
        } else {
            openURL(url);
        }
    }

    /**
     * Open an URL in the current Desktop Browser
     *
     * @param url
     */
    public static void openURL(String url) {
        try {
            String osName = System.getProperty("os.name");
            System.out.println("attempt to use Desktop library, Os name  : " + osName);
            // attempt to use Desktop library from JDK 1.6+
            Class<?> d = Class.forName("java.awt.Desktop");
            d.getDeclaredMethod("browse", new Class[]{java.net.URI.class}).invoke(d.getDeclaredMethod("getDesktop").invoke(null), new Object[]{java.net.URI.create(url)});
            // above code mimicks: java.awt.Desktop.getDesktop().browse()

        } catch (Exception ignore) {
            // library not available or failed
            String osName = System.getProperty("os.name");
            try {
                if (osName.startsWith("Mac OS")) {
                    //System.out.println("ERROR DesktopBrowser - Try to open file with com.apple.eio.FileManager.openURL()");
                    Class.forName("com.apple.eio.FileManager").getDeclaredMethod("openURL", new Class[]{String.class}).invoke(null, new Object[]{url});

                } else if (osName.startsWith("Windows")) {
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);

                } else {
                    // assume Unix or Linux
                    String browser = null;
                    for (String b : browsers) {
                        if (browser == null && Runtime.getRuntime().exec(new String[]{"which", b}).getInputStream().read() != -1) {
                            //Runtime.getRuntime().exec(new String[] { browser = b, url });
                            String[] cmd = new String[]{browser = b, url};
                            //System.out.println("Os name  : " + osName);
                            //System.out.println("Execute command : " + cmd);
                            Runtime.getRuntime().exec(cmd);
//							CommandLine commandLine = new CommandLine(b);
//							commandLine.addArgument(url, false);
//							launchCommand(commandLine, 1000, false);
                        }
                    }
                    if (browser == null) {
                        throw new Exception(Arrays.toString(browsers));
                    }
                }
            } catch (Exception e) {
                DialogBox.error(" Error while calling external interface.\nDesktop is not supported on this platform.");
            }
        }
    }

//	private static void launchCommand(CommandLine commandLine, long computeJobTimeout, boolean computeInBackground) throws ExecuteException, IOException {
//		int exitValue;
//		ExecuteWatchdog watchdog = null;
//	
//		// create the executor and consider the exitValue '0' as success
//		Executor executor = new DefaultExecutor();
//		executor.setExitValue(0);
//		
//		// create a watchdog if requested
//		if(computeJobTimeout > 0) {
//			watchdog = new ExecuteWatchdog(computeJobTimeout);
//			executor.setWatchdog(watchdog);
//		}
//	
//		try {
//			exitValue = executor.execute(commandLine);
//			System.out.println("Executing job has properly ended with exit value="+exitValue);
//		}
//		catch (Exception e) {
//			System.out.println("Executing job has ended with Error");
//			e.printStackTrace();
//		}
//	}
}
