package ec.gp.syntactic.simplification.numeric;

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

class MulOneRule implements IRule {

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

	}

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

		Mul m = (Mul) subtree;
		return (m.children[0] instanceof IConstant && ((IConstant<Double>) m.children[0]).getConstant() == 1.0)
				||
				(m.children[1] instanceof IConstant && ((IConstant<Double>) m.children[1]).getConstant() == 1.0);
	}

	@Override
	public GPNode replace(GPNode subtree) {
		assert subtree instanceof Mul: "The provided subtree is not rooted by Mul!";

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

		throw new UnsupportedOperationException("The provided subtree does not implement multiplication by 1.0");
	}

}
