/*
 * Galatea Dialog Manager:
 * (c)2003 Takuya NISHIMOTO (nishi@hil.t.u-tokyo.ac.jp)
 * Based on Phoenix By Takuya NISHIMOTO and Mitsuhiro KIZU
 *
 * $Id: BreakThread.java,v 1.9 2008/02/14 02:00:07 nishi Exp $
 */
package galatea.io;

import galatea.logger.Logger;
import galatea.outitem.BreakOutItem;
import galatea.outitem.OutItem;

import java.util.ArrayList;

public class BreakThread extends Thread {
	
	private Logger dbg = new Logger("BreakThread", 0);
	private ArrayList<IOutputEventListener> 
		listeners_ = new ArrayList<IOutputEventListener>();
	private long millis_ = 0;
	private boolean start_ = false;
	private boolean term_ = false;
	
	public BreakThread() {
		setName("BreakThread");
	}
	
	public void addOutputEventListener(IOutputEventListener l) {
		listeners_.add(l);
	}
	
	public synchronized void outputDeviceStart(OutItem obj) {
		if (obj instanceof BreakOutItem) {
			BreakOutItem bo = (BreakOutItem)obj;
			dbg.print("Break: outputDeviceStart");
			//Double ms = new Double(((Double)obj).doubleValue() * 1000.0);
			Double ms = new Double(bo.getArgAsDouble() * 1000.0);
			millis_ = ms.longValue();
			start_ = true;
			notify();
		}
	}
	
	public synchronized void outputDeviceStop(OutItem obj) {
		notify();
	}
	
	public synchronized void terminate() {
		term_ = true;
		notify();
	}
	
	public void run() {
		synchronized(this) {
			for(;;) {
				dbg.print("BreakThread wait");
				try {
					wait();
				} catch(Exception e) {e.printStackTrace();}
				
				if (start_) {
					dbg.print("Break Start : " + millis_ + " msec");
					// listener_.enqueueOutputEvent(DeviceEvent.newOutputBusyInstance("break"));
					for (int i = 0; i < listeners_.size(); i++) {
						((IOutputEventListener)listeners_.get(i))
							.enqueueOutputEvent(DeviceEvent.newOutputBusyInstance("break"));
						
					}
					try {
						wait(millis_);
					} catch(Exception e) {
						e.printStackTrace();
					}
					start_ = false;
					dbg.print("Break End : " + millis_ + " msec");
					// listener_.enqueueOutputEvent(DeviceEvent.newOutputReadyInstance("break"));
					for (int i = 0; i < listeners_.size(); i++) {
						((IOutputEventListener)listeners_.get(i))
							.enqueueOutputEvent(DeviceEvent.newOutputReadyInstance("break"));
					}
				} 
				
				if (term_) {
					break;
				}
				
			}
		}
		
		dbg.print("BreakThread exitting...");
		
	}
	
}
