/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 Board of Regents of the University of
 * Wisconsin-Madison and University of Konstanz.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package net.imagej.ops.equation;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import net.imagej.ops.AbstractStrictFunction;
import net.imagej.ops.Op;
import net.imagej.ops.Ops;
import net.imglib2.Cursor;
import net.imglib2.IterableInterval;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.type.numeric.RealType;

import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.script.ScriptLanguage;
import org.scijava.script.ScriptService;

/**
 * Computes an image using an equation.
 * <p>
 * The equation is evaluated using Javascript. The image's position coordinates
 * are available to the equation via the {@code p} array; e.g.:
 * {@code Math.cos(0.1*p[0]) + Math.sin(0.1*p[1])}.
 * </p>
 * <p>
 * Note that this op is rather slow; it is intended mainly for demonstration
 * purposes, and to easily generate small images for testing OPS workflows.
 * </p>
 * 
 * @author Curtis Rueden
 */
@Plugin(type = Op.class, name = Ops.Equation.NAME)
public class DefaultEquation<T extends RealType<T>> extends
	AbstractStrictFunction<String, IterableInterval<T>> implements Equation<T>
{

	@Parameter
	private ScriptService scriptService;

	@Parameter
	private LogService log;

	@Override
	public IterableInterval<T> compute(final String input,
		final IterableInterval<T> output)
	{
		final IterableInterval<T> image;
		if (output == null) {
			// produce a 256x256 float64 array-backed image by default
			@SuppressWarnings({ "rawtypes", "unchecked" })
			final IterableInterval<T> newImage =
				(IterableInterval) ArrayImgs.doubles(256, 256);
			image = newImage;
		}
		else image = output;

		final String equation = input + ";";

		// evaluate the equation using Javascript!
		final ScriptLanguage js = scriptService.getLanguageByName("javascript");
		final ScriptEngine engine = js.getScriptEngine();
		final Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);

		final Cursor<T> c = image.localizingCursor();
		final long[] pos = new long[image.numDimensions()];
		bindings.put("p", pos);

		try {
			while (c.hasNext()) {
				c.fwd();
				c.localize(pos);
				final Object o = engine.eval(equation);
				final double d =
					o instanceof Number ? ((Number) o).doubleValue() : Double.NaN;
				c.get().setReal(d);
			}
		}
		catch (final ScriptException exc) {
			log.error(exc);
		}
		return image;
	}

}

@@ -1705,37 +1705,37 @@
 gej.ops.Abstract
-Stric
+Outpu
 tFunction;%0Aimpor
@@ -2699,13 +2699,13 @@
 ract
-Stric
+Outpu
 tFun
@@ -2854,16 +2854,50 @@
 e log;%0A%0A
+%09// -- OutputFunction methods --%0A%0A
 %09@Overri
@@ -2932,136 +2932,38 @@
 T%3E c
-ompute(final String input,%0A%09%09final IterableInterval%3CT%3E output)%0A%09%7B%0A%09%09final IterableInterval%3CT%3E image;%0A%09%09if (output == null
+reateOutput(String input
 ) %7B%0A%09%09
-%09
 // p
@@ -3017,17 +3017,16 @@
 default%0A
-%09
 %09%09@Suppr
@@ -3068,17 +3068,16 @@
 d%22 %7D)%0A%09%09
-%09
 final It
@@ -3105,17 +3105,16 @@
 Image =%0A
-%09
 %09%09%09(Iter
@@ -3162,16 +3162,14 @@
 ;%0A%09%09
-%09image =
+return
  new
@@ -3180,34 +3180,139 @@
 e;%0A%09
-%09%7D%0A%09%09else image =
+%7D%0A%0A%09// -- Internal methods --%0A%0A%09@Override%0A%09protected IterableInterval%3CT%3E safeCompute(String input,%0A%09%09IterableInterval%3CT%3E
  output
-;%0A
+)%0A%09%7B
 %0A%09%09f
@@ -3619,21 +3619,22 @@
 %3CT%3E c = 
-image
+output
 .localiz
@@ -3676,21 +3676,22 @@
 ew long%5B
-image
+output
 .numDime
@@ -4031,21 +4031,22 @@
 %09return 
-image
+output
 ;%0A%09%7D%0A%0A%7D%0A

extend OutputFunction