package ec.app.semanticGP.func.numeric;

import java.util.List;

import ec.gp.GPNode;
import library.semantics.TestCase;
import ec.EvolutionState;
import ec.gp.semantic.DoubleSemantics;
import ec.gp.semantic.ISemanticProblem;
import ec.gp.semantic.ISemantics;
import ec.gp.semantic.func.NullaryNode;
import ec.util.Parameter;

public class Xn extends NullaryNode<Double> {
	private final static GPNode[] EMPTY_CHILDREN = new GPNode[0];
	private final static Xn[] CACHE = new Xn[256];

	private final byte n;

	protected Xn(byte n) {
		this.n = n;
		this.children = EMPTY_CHILDREN;
	}

	public static Xn get(byte n) {
		int idx = n - Byte.MIN_VALUE; // handle negative values
		if (CACHE[idx] == null) {
			CACHE[idx] = new Xn(n);
		}
		return CACHE[idx];
	}

	@Override
	public void setup(EvolutionState state, Parameter base) {
		super.setup(state, base);
	}

	@Override
	public int nodeHashCode() {
		return super.nodeHashCode() ^ this.n;
	}

	@Override
	public boolean nodeEquals(GPNode node) {
		if (!(node instanceof Xn)) {
			return false;
		}

		Xn other = (Xn) node;
		return this.n == other.n;
	}

	@Override
	protected ISemantics execute(ISemantics... arguments) {
		ISemanticProblem<Double> problem = (ISemanticProblem<Double>) this.state.evaluator.p_problem;
		List<TestCase<Double>> cases = problem.getFitnessCases();

		double[] semantics = new double[cases.size()];
		for (int i = 0; i < cases.size(); ++i) {
			semantics[i] = cases.get(i).getArguments()[this.n];
		}

		return new DoubleSemantics(semantics);
	}

	@Override
	public String toString() {
		return ("X" + this.n).intern();
	}

	/*@Override
	public Object clone() {
		// this object is immutable, we don't need to copy its memory
		return this;
	}

	@Override
	public GPNode lightClone() {
		// this object is immutable, we don't need to copy its memory
		return this;
	}

	/*@Override
	public int atDepth() {
		// we cannot determine it, since all clones are the same object
		return Integer.MIN_VALUE;
	}*/
}
