package org.jcon.test.app3;

import org.jcon.df.edit.EditEvent;
import org.jcon.df.work.Row;
import org.jcon.df.work.RowSource;
import org.jcon.df.work.RowSet;
import org.jcon.df.work.RowSetListener;
import java.util.Vector;

/**
 * This class is the source of rows for a RowEditor.
 * (A test RowSource for evolving a set of components.)
 *
 * @author Jack Harich
 */
public class TestRowSource implements RowSource {

//---------- Private Fields ------------------------------
// Properties
private String   sourceID;
private String   entityName;
// Internal
private RowSet   rowSet = new RowSet();
private Row      testRow = new Row();

//---------- RowSource Implementation --------------------
//---------- Events    
public void addRowSetListener(RowSetListener listener) {
    rowSet.addRowSetListener(listener);       
}
public void removeRowSetListener(RowSetListener listener) {
    rowSet.removeRowSetListener(listener);    
}
//---------- Properties 
//----- ID
public void setID(String sourceID) {
    this.sourceID = sourceID;
}
public String getID() {
    return sourceID;
}
//----- entityName
public void setEntityName(String entityName) {
    this.entityName = entityName;   
}    
public String getEntityName() {
    return entityName;   
}    
//---------- Public Methods 
/**
 * The source should start working and fire initialization
 * related events that cause the view to be initially populated.
 */
public void start() {
    //print(".start() - Entered - Simulating get 1 row");
    // Populate testRow
    testRow.setValue("UserSys.UserID", "J01");
    testRow.setValue("UserSys.IsAdmin", "1");
    // Create rows
    Vector rows = new Vector();
    rows.addElement(testRow);
    // Pass rows to rowSet - The magic call that does alot
    // Will cause views to populate themselves via events
    rowSet.replaceAllRows(rows);    
}    
public void processEditEvent(EditEvent evt) {
    //print(".processEditEvent() - " + evt.getEventTypeString());
    
    // Just a few to illustrate we're cooking...
    switch(evt.getEventType()) {
        case EditEvent.BEGIN_CHANGE:
            rowSet.beginChangeRow();
            break;        
        case EditEvent.OKAY_CHANGE:
            commitChangeRow(evt);
            break; 
        case EditEvent.CANCEL_CHANGE:
            rowSet.rollbackChangeRow();
            break;            
    }
}    
//---------- Private Methods -----------------------------
private void commitChangeRow(EditEvent evt) {
    Row row = rowSet.acquireEditRow();
    // Validate with schema later ***
    
    // Simulate server update
    testRow.copy(row);
       
    // Assume update successful
    rowSet.commitChangeRow(testRow);
}    
//--- Std
private static void print(String text) {
    System.out.println("TestRowSource" + text);
}

} // End class
