package org.openlca.app.util;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.widgets.Composite;
import org.openlca.app.App;
import org.openlca.app.preferencepages.FeatureFlag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class BrowserFactory {

	private static Logger log = LoggerFactory.getLogger(BrowserFactory.class);

	private static boolean useXulRunner = false;
	private static boolean initialized = false;

	public static Browser create(Composite parent) {
		if (!initialized)
			initialize();
		Browser browser = null;
		if (useXulRunner) {
			log.trace("Create Mozilla browser");
			browser = createMozilla(parent);
		} else {
			log.trace("Create system browser");
			browser = new Browser(parent, SWT.NONE);
		}
		browser.setJavascriptEnabled(true);
		return browser;
	}

	private static void initialize() {
		log.trace("initialize browser factory");
		if (!FeatureFlag.USE_MOZILLA_BROWSER.isEnabled()) {
			useXulRunner = false;
			return;
		}
		try {
			String xulRunnerPath = App.getXulRunnerPath();
			if (xulRunnerPath == null) {
				log.trace("No XUL runner found, use system browser");
				useXulRunner = false;
			} else {
				log.trace("Use Mozilla browser, XUL runner found at {}",
						xulRunnerPath);
				System.setProperty("org.eclipse.swt.browser.XULRunnerPath",
						xulRunnerPath);
				useXulRunner = true;
			}
		} catch (Exception e) {
			log.error("Failed to initialize browser factory");
		} finally {
			initialized = true;
		}
	}

	private static Browser createMozilla(Composite parent) {
		try {
			return new Browser(parent, SWT.MOZILLA);
		} catch (Throwable e) {
			log.warn(
					"Failed to create Mozilla browser, fall back to system default",
					e);
			useXulRunner = false;
			return new Browser(parent, SWT.NONE);
		}
	}

}

@@ -214,16 +214,44 @@
 reFlag;%0A
+import org.openlca.util.OS;%0A
 import o
@@ -263,24 +263,24 @@
 f4j.Logger;%0A
-
 import org.s
@@ -952,49 +952,26 @@
 f (!
-FeatureFlag.USE_MOZILLA_BROWSER.isEnabled
+shouldUseXulRunner
 ()) 
@@ -989,32 +989,55 @@
 Runner = false;%0A
+%09%09%09initialized = true;%0A
 %09%09%09return;%0A%09%09%7D%0A%09
@@ -1537,24 +1537,24 @@
 = true;%0A
-
 %09%09%7D%0A%09%7D%0A%0A
 %09private
@@ -1541,24 +1541,188 @@
 ue;%0A%09%09%7D%0A%09%7D%0A%0A
+%09private static boolean shouldUseXulRunner() %7B%0A%09%09if (OS.getCurrent() == OS.Linux)%0A%09%09%09return true;%0A%09%09else%0A%09%09%09return FeatureFlag.USE_MOZILLA_BROWSER.isEnabled();%0A%09%7D%0A%0A
 %09private sta

use always embedded XulRunner under Linux