package ec.gp.syntactic.simplification.numeric;

import ec.EvolutionState;
import ec.app.semanticGP.func.IConstant;
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 SumSubZeroRule implements IRule {

	@Override
	public void setup(EvolutionState state, Parameter base) {
		// TODO Auto-generated method stub

	}

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

		if (subtree.children[0] instanceof Sub) {
			return subtree.children[0].children[0] instanceof IConstant
					&& ((IConstant<Double>) subtree.children[0].children[0]).getConstant() == 0.0;
		} else if (subtree.children[1] instanceof Sub) {
			return subtree.children[1].children[0] instanceof IConstant
					&& ((IConstant<Double>) subtree.children[1].children[0]).getConstant() == 0.0;
		}

		return false;
	}

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

		Sub sub = new Sub();

		if (subtree.children[0] instanceof Sub) {

			sub.children = new GPNode[] { subtree.children[1], subtree.children[0].children[1] };

		} else {
			assert subtree.children[1] instanceof Sub;

			sub.children = new GPNode[] { subtree.children[0], subtree.children[1].children[1] };
		}

		return sub;
	}

}
