package org.jcon.df.request;

//import org.jcon.df.Entity;
import org.jcon.df.work.Row;
import org.jcon.util.DataLib;
import org.jcon.param.Param;
import org.jcon.test.TestJDBC;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Vector;

/**
 * A request to read a row from the database.
 *
 * @author Jack Harich
 */
public class ReadRow extends DataRequest {

//---------- Private Fields ------------------------------
private Row row;

//---------- Initialization ------------------------------
public static void main(String args[]) {
    new ReadRow().runUnitTest();
}
//---------- Abstract Implementation ---------------------
public boolean isMutator() {
    return false;
}
public Object perform() {
    String sql = null;
    try {
        // Prepare reader  - set properties, execute
        ResultSetReader reader = new ResultSetReader();
        reader.setSchema(requestServices.getSchema());
        String[] colIDs = DataLib.convertVectorToStringArray(getColumnIDs());
        reader.setColumnIDs(colIDs);
        reader.setStatement(requestServices.getStatement());
        // Get sql and execute
        sql = requestServices.getTranslator()
            .buildSelectStm(this);
        //print(".perform() - translator built sql = " + sql);
        reader.setSQL(sql);
        reader.execute();
        // Use reader
        row = reader.nextRow();

    } catch(Exception ex) {
        //ex.printStackTrace();
        this.setFailureText("Failure with SQL=" + sql);
        this.setFailureSQL(sql);
        this.setFailureException(ex);
    }
    return this;
}
//---------- Properties ----------------------------------
/**
 * Returns the first row or null if none.
 */
public Row getRow() {
    return row;
}
//---------- Public Methods ------------------------------
//----- Other
public void runUnitTest() {
    TestJDBC tester = new TestJDBC();

    // Prepare reader
    ReadRow reader = new ReadRow();
    reader.addColumnID("SysUser.MID");
    reader.addColumnID("SysUser.FirstName");
    reader.addColumnID("SysUser.LastLogon");
    reader.addEntity("SysUser");

    // Cannot filter since translator has no schema
    //reader.getFilter().addExpression("SysUser.MID",
     //   "=", "2");

    // No need to set Translator properties
    reader.perform();
    // Use reader
    print(" - Row = " + reader.getRow());
    // Done
    tester.close();
}
//---------- Properties ----------------------------------

//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    System.out.println("ReadRow" + text);
}

} // End class
