package ec.gp.syntactic.simplification.numeric;

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

class SumZeroRule implements IRule {

	@Override
	public void setup(EvolutionState state, Parameter base) {

	}

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

		Sum s = (Sum) subtree;
		return (s.children[0] instanceof IConstant && ((IConstant<Double>) s.children[0]).getConstant() == 0.0)
				||
				(s.children[1] instanceof IConstant && ((IConstant<Double>) s.children[1]).getConstant() == 0.0);
	}

	@Override
	public GPNode replace(GPNode subtree) {
		assert subtree instanceof Sum : "Given tree is not rooted by Sum";

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

		throw new UnsupportedOperationException("Given tree is not Sum of 0 and other value");
	}

}
