import java.util.*;

public class Agent extends Thread implements Triggerable {

	Object monitor;
	Timer timer;
	Space space;
	int sleepPeriod = 0;

	public Agent () {
		monitor = new Object();
		timer = new Timer(true);
		space = Space.getInstance();
		start();
	}

	public void attachTimer(int period) {
		// to be called from init()
		timer.scheduleAtFixedRate( new TimerTask() {
			public void run() {
				trigger();
			}
		},period,period);
	}

	public void attachTrigger(String name) {
		// to be called from init()
		space.registerTrigger(name,this);
	}

	public void setSleep(int period) {
		// to be called from init()
		sleepPeriod = period;
	}

	void init() {
		// to be overriden
	}

	void senseSelectAct() {
		// to be overriden
	}

	private int receive() {
		int ret = 0;
		synchronized(monitor) {
			try {
				monitor.wait();
			}
			catch (InterruptedException e) {
				ret = -1;
			}
		}
		return (ret);
	}

	public void trigger() {
		synchronized (monitor) {
			monitor.notifyAll();
		}
	}

	public void write (String name, Object value) {
		space.write(name,value);
	}

	public void write (String name, Object value, double validity) {
		space.write(name,value,validity);
	}

	public void write (String name, Object value, double validity, float priority) {
		space.write(name,value,validity,priority);
	}

	public Object read (String name) {
		return space.read(name);
	}

	public Object read (String name, Object deflt) {
		return space.read(name,deflt);
	}

	public void delay (int ms) {
		try {
			Thread.sleep(ms);
		} catch (InterruptedException e) {
		}
	}

	public void run () {
		init();
		for (;;) {
			if (sleepPeriod > 0) delay(sleepPeriod);
			else receive();
			senseSelectAct();
		}
	}

}