/**
 * Copyright © 2012-2020 by Data Virtuality GmbH
 */
package org.teiid.query.scripts;

import com.oracle.truffle.js.scriptengine.GraalJSEngineFactory;
import org.teiid.query.scripts.python.PythonScriptEngineFactory;

import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

/**
 * Increases priority of GraalJS engine factory among other factories
 *
 * @author Dmitry Pogorelov
 * @date 2020.09.14
 */
public class TeiidScriptEngineManager extends ScriptEngineManager {
	public TeiidScriptEngineManager() {
		super();
		registerGraalJSEngines();
		registerGraalPythonEngine();
	}

	public TeiidScriptEngineManager(ClassLoader loader) {
		super(loader);
		registerGraalJSEngines();
		registerGraalPythonEngine();
	}

	private void registerGraalJSEngines() {
		GraalJSEngineFactory jsspi = new GraalJSEngineFactory();
		registerScriptEngineFactory(jsspi);
	}

	private void registerGraalPythonEngine() {
		PythonScriptEngineFactory pspi = new PythonScriptEngineFactory();
		registerScriptEngineFactory(pspi);
	}

	private void registerScriptEngineFactory(ScriptEngineFactory factory) {
		for (String name : factory.getNames()) {
			registerEngineName(name, factory);
		}

		for (String type : factory.getMimeTypes()) {
			registerEngineMimeType(type, factory);
		}

		for (String extension : factory.getExtensions()) {
			registerEngineExtension(extension, factory);
		}
	}
}
