package org.jcon.util.lock;

/**
 * Represents a client using the LockPool for transactions.
 *
 * @author Jack Harich
 */
public class TestClient implements Runnable {

//---------- Private Fields ------------------------------
private TestViewClient view;
private LockPool       lockPool;
private String[]       names;

//---------- Runnable Implementation ---------------------
public void run() {
    doTransaction();
}
//---------- Properties ----------------------------------
public void setLockPool(LockPool lockPool) {
    this.lockPool = lockPool;
}
public void setTestViewClient(TestViewClient view) {
    this.view = view;
}
public void setObjectNames(String[] names) {
    this.names = names;
}
//---------- Public Methods ------------------------------
public void start() {
    new Thread(this).start();
}
//---------- Private Methods -----------------------------
// Note importance of unlock() in finally and checking to
// see if lockSet is null.
private void doTransaction() {
    LockSet lockSet = null;
    try {
        //----- Acquire lockSet
        view.changeWaitCount(1);
        try {
            lockSet = lockPool.lockObjects((Object[])names);
        } catch(Exception ex) {
            // lockSet will be null
            ex.printStackTrace();
        }
        view.changeWaitCount(-1);
        if (lockSet != null) {
            //----- Perform transaction
            view.setWorking(true);
            view.setCellCount(names.length);
            view.getColorBar().setFullCount(0);

            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                TestTask task = (TestTask)lockSet.get(name);
                view.getColorBar().incrementFullCount();
                // Next line will block awhile
                task.perform();
            }
        }
    } finally {
        //----- Done
        if (lockSet != null) lockPool.unlock(lockSet);
        view.setWorking(false);
        view.getColorBar().setFullCount(0);
    }
}
//--- Std
private static void print(String text) {
    System.out.println("TestClient" + text);
}

} // End class
