/*
 * bondTupleSpaceEnabledGuiStrateyg.java
 * @contains allows agents to access data through
 *     Tuplespace. Classes that are able to access
 *     the Tuplespace and provide GUI should be
 *     extended from this class.
 *
 * @author Kyungkoo Jun
 * Bond group, CS, Purdue Univ.
 * @date  Oct. 20, 2000
 *
 * modified by Kyungkoo Jun Nov 2, 2000
 *   --- rename setToTupleSpace() into putIntoTupleSpace()
 */
package bond.agent.strategydb;

import com.ibm.tspaces.*;
import bond.agent.*;
import bond.agent.interfaces.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

/*
  Strategies extending this strategy are able to
  communicate with other agents through TupleSpace
  TupleSpace was implemented by using IBM's TSpace
 */

public class bondTupleSpaceEnabledGuiStrategy
extends bondGuiStrategy
{

  TupleSpace space;
  boolean inited = false;
  String transition;
  Object blocked = new Object();

  public Object getFromTupleSpace(String s) {
    try {
      Tuple msg = space.waitToTake(s, new Field(Serializable.class));
      if (msg != null) {
	return (Object)msg.getField(1).getValue();
      }
      else {
	return null;
      }
    }
    catch (TupleSpaceException e) {
      return null;
    }
    catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public Object copyFromTupleSpace(String s) {
    try {
      Tuple msg = space.waitToRead(s, new Field(Serializable.class));
      if (msg != null) {
	return (Object)msg.getField(1).getValue();
      }
      else {
	return null;
      }
    }
    catch (TupleSpaceException e) {
      return null;
    }
    catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public boolean putIntoToTupleSpace(String s, Serializable o) {
    try {
      space.write(s, o);
      return true;
    }
    catch (TupleSpaceException e) {
      return false;
    }
    catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  public boolean setTupleSpace(String host, String sname) {
    try {
      space = new TupleSpace(sname, host);
      return true;
    }
    catch (TupleSpaceException e) {
      return false;
    }
    catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  public void install(bondFiniteStateMachine fsm) {

    if (!inited) {
      super.install(fsm);
      String host = (String)getModel("TupleServer");
      String sname = (String)getModel("SpaceName");
      if (host == null || sname == null) {
	inited = true;
	return;
      }
      inited = setTupleSpace(host, sname);
    }
  }

  public void uninstall() {
    // do nothing
  }

  public long action(bondModel m, bondAgenda a) {
    try {
      synchronized(blocked) {
	blocked.wait();
      }
    }
    catch (InterruptedException e) {
    }
    transition(transition);
    return 0l;
  }

  public void move(String s) {
    transition = s;
    synchronized(blocked) {
      blocked.notify();
    }
  }


}
