package ec.gp.syntactic.simplification.numeric;

import ec.EvolutionState;
import ec.app.semanticGP.func.numeric.Constant;
import ec.app.semanticGP.func.numeric.Sub;
import ec.app.semanticGP.func.numeric.Sum;
import ec.gp.GPNode;
import ec.gp.syntactic.simplification.IRule;
import ec.util.Parameter;

class SubSumRule implements IRule {

	private EvolutionState state;

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

	@Override
	public boolean match(GPNode subtree) {
		if (!(subtree instanceof Sub))
			return false;

		if (!(subtree.children[1] instanceof Sum))
			return false;

		return subtree.children[0].rootedTreeEquals(subtree.children[1].children[0])
				||
				subtree.children[0].rootedTreeEquals(subtree.children[1].children[1]);
	}

	@Override
	public GPNode replace(GPNode subtree) {
		assert match(subtree) : "The given tree is not a form of (a - (a + b))";

		Constant constant = Constant.ZERO;
		Sub sub = new Sub();
		if (subtree.children[0].rootedTreeEquals(subtree.children[1].children[0])) {
			sub.children = new GPNode[] { constant, subtree.children[1].children[1] };
		} else {
			assert subtree.children[0].rootedTreeEquals(subtree.children[1].children[1]);
			sub.children = new GPNode[] { constant, subtree.children[1].children[0] };
		}

		return sub;
	}

}
