/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package expressiontree.operators.binary;

import expressiontree.ExpressionTreeElement;
import expressiontree.operands.NumberType;
import expressiontree.operators.BinaryOperator;
import expressiontree.operators.IncompatibleNumberFormatException;
import org.apfloat.Apfloat;
import org.apfloat.ApfloatMath;

/**
 * A hatványozás operátorok osztálya.
 * @author Esta
 */
public class RaiseToPower extends BinaryOperator {

    @Override
    public ExpressionTreeElement getValue() throws IncompatibleNumberFormatException {
        ExpressionTreeElement op1 = this.operands.get(0).getValue();
        ExpressionTreeElement op2 = this.operands.get(1).getValue();
        if (op1 instanceof NumberType && op2 instanceof NumberType) {
            //csak akkor lehet számolni, ha számot találtunk
            NumberType a = (NumberType) op1;
            NumberType b = (NumberType) op2;
            NumberType retValue = new NumberType(this.precision,false);
            try {
                if (b.isLongValue()) {
                    retValue.setValue(ApfloatMath.pow(a.getNumericValue(), b.getNumericValue().longValue()));
                } else {
                    retValue.setValue(ApfloatMath.pow(a.getNumericValue(), b.getNumericValue()));
                }
            } catch (ArithmeticException arithmeticException) {
                if (a.getNumericValue().compareTo(b.getNumericValue())==0 && a.getNumericValue().compareTo(new Apfloat(0.0,2))==0)
                    throw new ArithmeticException("POW_X_IS_ZERO_AND_Y_IS_ZERO");
                else
                    throw new ArithmeticException("POW_X_IS_BELOW_ZERO");
            }
            return retValue;
        } else { //mátrix >> exception
            throw new IncompatibleNumberFormatException("ERROR_POW");
        }
    }

    @Override
    public String toText(boolean b) {
        if (b) {
            return "() ^ ()";
        } else {
            return "^ ";
        }
    }

    @Override
    public String getLocalizedName() {
        return java.util.ResourceBundle.getBundle("languages/operators").getString("POWER");
    }
}
