package ac.essex.gp.nodes;

import ac.essex.gp.tree.Node;
import ac.essex.gp.params.NodeParams;
import ac.essex.gp.util.DataStack;
import ac.essex.gp.nodes.ercs.BasicERC;

/**
 * <p/>
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version,
 * provided that any use properly credits the author.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details at http://www.gnu.org
 * </p>
 *
 * @author Olly Oechsle, University of Essex, Date: 17-Jan-2007
 * @version 1.0
 */
public class If extends Node {

    public If() {
        super(3);
    }

    public int getReturnType() {
        return NodeParams.SUBSTATEMENT;
    }

    public int getChildType(int index) {
        switch (index)  {
            case 0:
                return NodeParams.BOOLEAN;
            default:
                return NodeParams.SUBSTATEMENT;
        }
    }

    public double execute(DataStack data) {
        data.value = child[0].execute(data);
        if (data.value == 1) {
            data.value = child[1].execute(data);
        } else {
            data.value = child[2].execute(data);
        }
        return debugger.record(data.value);
    }

    public Node optimise() {
        if (child[1].debugger.neverExecuted()) {
            // it would appear that the program would work just as well if we just returned
            // the second tree and removed the if statement all together
            replaceMyselfWith(child[2]);
            return child[2];
        }
        if (child[2].debugger.neverExecuted()) {
            // it would appear that the program would work just as well if we just returned
            // the first tree and removed the if statement all together
            replaceMyselfWith(child[1]);
            return child[1];
        }
        return this;
    }

    public String toJava() {
        String expression = child[0].getName();
        if (child[0] instanceof BasicERC) {
            // if it was replaced by an ERC by the optimiser there will just be
            // 0.0, or 1.0, which won't compile. Convert this to "true" or "false";
            double d = ((ac.essex.gp.nodes.ercs.BasicERC) child[0]).getValue();
            if (d == 1.0) {
                expression = "true";
            }
            if (d == 0.0) {
                expression = "false";
            }
        }
        return expression + "? " + child[1].getName() + " : " + child[2].getName();
    }

}
