package ec.gp.syntactic.simplification.numeric;

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

class MulPowConstRule implements IRule {

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

	}

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

		if (subtree.children[0] instanceof IConstant && subtree.children[1] instanceof Pow) {

			return subtree.children[1].children[1] instanceof IConstant
					&& ((IConstant<Double>) subtree.children[1].children[1]).getConstant() == -1.0;

		} else if (subtree.children[1] instanceof IConstant && subtree.children[0] instanceof Pow) {

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

		}

		return false;
	}

	@Override
	public GPNode replace(GPNode subtree) {
		assert match(subtree) : "The given tree is not a form of (const * (p^-1)) or ((p^-1) * const)";

		Div div = new Div();

		if (subtree.children[0] instanceof IConstant && subtree.children[1] instanceof Pow) {
			div.children = new GPNode[] { subtree.children[0], subtree.children[1].children[0] };

		} else if (subtree.children[1] instanceof IConstant && subtree.children[0] instanceof Pow) {
			div.children = new GPNode[] { subtree.children[1], subtree.children[0].children[0] };

		}

		throw new UnsupportedOperationException("The given tree is not a form of (const * (p^-1)) or ((p^-1) * const)");
	}

}
