package ec.app.semanticGP.func.classification;

import ec.gp.GPNode;
import ec.gp.semantic.ByteSemantics;
import ec.gp.semantic.DoubleSemantics;
import ec.gp.semantic.ISemanticProblem;
import ec.gp.semantic.ISemantics;
import ec.gp.semantic.func.NullaryNode;
import library.semantics.TestCase;

import java.util.List;

/**
 * Attribute n
 */
public class An extends NullaryNode<Byte> {
	private final static GPNode[] EMPTY_CHILDREN = new GPNode[0];
	private final static An[] CACHE = new An[256];

	protected final byte n;

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

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

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

		An other = (An)node;
		return super.nodeEquals(node) && this.n == other.n;
	}

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

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

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

		return new ByteSemantics(semantics);
	}

	@Override
	public String toString() {
		return ("A" + 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;
	}
}
