package org.jcon.df.request;

// import org.jcon.util.GenLib;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * A request to calculate using an aggregate function.
 * These are COUNT, SUM, AVERAGE, MIN, MAX.
 *
 * @author Jack Harich
 */
public class CalcAggregate extends DataRequest {

//---------- Private Fields ------------------------------
private double answer = Double.NEGATIVE_INFINITY;
private String sql;

//---------- Abstract Implementation ---------------------
public boolean isMutator() {
    return false;
}
public Object perform() {
    if (sql == null) prepare();
    try {
        answer = 0;
        ResultSet rs = requestServices.getStatement()
            .executeQuery(sql);
        while (rs.next()) {
            answer = rs.getDouble(1);
            break;
        }
    } catch(Exception ex) {
        ex.printStackTrace();
        //print(".perform() - Exception: " + ex.getMessage());
        answer = Double.NEGATIVE_INFINITY;
        this.setFailureText("Exception, table may not be in database");
        this.setFailureSQL(sql);
        this.setFailureException(ex);
    }
    return this;
}
//---------- Superclass Overrides ------------------------
public void prepare() {
    try {
        sql = requestServices.getTranslator()
            .buildAggregateStm(this);

    } catch(Exception ex) {
        ex.printStackTrace();
        answer = Double.NEGATIVE_INFINITY;
        this.setFailureText("Cannot translate to SQL.");
        this.setFailureException(ex);
        throw new IllegalStateException("Cannot translate to SQL.");
    }
}
//---------- Properties ----------------------------------
/**
 * Returns the answer, which is Double.NEGATIVE_INFINITY if
 * failure or zero if empty.  This calculation
 * result must be accessed AFTER the request is performed.
 */
public double getAnswerAsDouble() {
    return answer;
}
/**
 * A convenience method that returns the answer as an int.
 * This drops anything to the right of the decimal.
 */
public int getAnswerAsInt() {
    return new Double(answer).intValue();
}
/**
 * A convenience method that returns the answer as a long.
 * This drops anything to the right of the decimal.
 */
public long getAnswerAsLong() {
    return new Double(answer).longValue();
}
//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    System.out.println("CalcAggregate" + text);
}

} // End class
