package org.drpowell.vcffilters;

import java.io.Reader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.drpowell.vcf.VCFIterator;
import org.drpowell.vcf.VCFVariant;

public class ScriptVCFFilter extends VCFFilteringIterator {

	private Invocable invocable;
	
	private Invocable initializeEngine(Reader script) {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("JavaScript");
		try {
			engine.eval(script);
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			System.err.println("Error preparing filter, will pass all variants!\n" + e);
			engine = null;
		}
		return (Invocable) engine;
	}

	public ScriptVCFFilter(VCFIterator client, Reader fileReader) {
		super(client);
		invocable = initializeEngine(fileReader);
	}

	@Override
	public VCFVariant filter(VCFVariant variant) {
		if (invocable == null) return variant;
		try {
			return (VCFVariant) invocable.invokeFunction("filter", variant);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			return variant;
		} catch (ScriptException e) {
			e.printStackTrace();
			return variant;
		}
	}

}

@@ -49,16 +49,72 @@
 .Reader;
+%0Aimport java.util.List;%0Aimport java.util.logging.Logger;
 %0A%0Aimport
@@ -251,16 +251,52 @@
 ption;%0A%0A
+import org.drpowell.vcf.VCFHeaders;%0A
 import o
@@ -324,16 +324,49 @@
 erator;%0A
+import org.drpowell.vcf.VCFMeta;%0A
 import o
@@ -485,16 +485,45 @@
 ocable;%0A
+%09private VCFHeaders headers;%0A
 %09%0A%09priva
@@ -895,16 +895,496 @@
 ll;%0A%09%09%7D%0A
+%09%09Object moreHeaders = engine.get(%22headers%22);%0A%09%09if (moreHeaders != null) %7B%0A%09%09%09if (moreHeaders instanceof String) %7B%0A%09%09%09%09for (String header : ((String) moreHeaders).split(%22%5Cn%22)) %7B%0A%09%09%09%09%09headers.add(new VCFMeta(header));%0A%09%09%09%09%7D%0A%09%09%09%7D else if (moreHeaders instanceof List) %7B%0A%09%09%09%09for (Object header : (List) moreHeaders) %7B%0A%09%09%09%09%09headers.add(new VCFMeta(header.toString()));%0A%09%09%09%09%7D%0A%09%09%09%7D else %7B%0A%09%09%09%09Logger.getLogger(%22VARITAS%22).warning(%22Unable to add headers for javascript filter%22);%0A%09%09%09%7D%0A%09%09%7D%0A
 %09%09return
@@ -1473,16 +1473,16 @@
 ader) %7B%0A
-
 %09%09super(
@@ -1490,16 +1490,49 @@
 lient);%0A
+%09%09headers = client.getHeaders();%0A
 %09%09invoca

support for additional headers in javascript filter