package gnu.javax.sound.sampled.wce;

import java.util.ArrayList;
import java.util.List;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;

class WCEEventQueue implements Runnable {
	/**
	 * LineEventキュー
	 */
	private final List eventList = new ArrayList();

	/**
	 * 次のイベントを返す
	 */
	private LineEvent getNextEvent() {
		LineEvent event = null;
		try {
			synchronized (this.eventList) {
				while (this.eventList.size() <= 0) {
					this.eventList.wait();
				}
				event = (LineEvent) this.eventList.get(0);
				this.eventList.remove(0);
			}
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
		return event;
	}

	/**
	 * イベントをキューにポストする
	 */
	public void postEvent(Line line, LineEvent.Type type, long position) {
		LineEvent event = new LineEvent(line, type, position);
		synchronized (this.eventList) {
			this.eventList.add(event);
			this.eventList.notifyAll();
		}
	}

	public void run() {
		while (true) {
			try {
				LineEvent event = getNextEvent();
				Line line = event.getLine();
				if (line instanceof WCELine) {
					WCELine wline = (WCELine) line;
					wline.notifyLineEvent(event);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
