/*
 * Copyright 2006 Phidgets Inc.  All rights reserved.
 */

package com.phidgets;
import java.util.Iterator;
import java.util.LinkedList;
import com.phidgets.event.*;
public final class EncoderPhidget extends Phidget {
	public EncoderPhidget() throws PhidgetException {
		super(create());
	}
	private static native long create() throws PhidgetException;
	public native int getEncoderCount() throws PhidgetException;
	public native int getInputCount() throws PhidgetException;
	public native int getEncoderPosition(int index) throws PhidgetException;
	public native void setEncoderPosition(int index, int position) throws PhidgetException;
	public native boolean getInputState(int index) throws PhidgetException;

	protected final void enableDeviceSpecificEvents (boolean b) {
		enableEncoderPositionChangeEvents (b && encoderPositionChangeListeners.size () > 0);
		enableInputChangeEvents (b && inputChangeListeners.size () > 0);
	}
	private LinkedList encoderPositionChangeListeners = new LinkedList();
	private long nativeEncoderPositionChangeHandler = 0;
	public final void addEncoderPositionChangeListener(EncoderPositionChangeListener l) {
		synchronized (encoderPositionChangeListeners) {
			encoderPositionChangeListeners.add(l);
			enableEncoderPositionChangeEvents(true);
		}
	}
	public final void removeEncoderPositionChangeListener(EncoderPositionChangeListener l) {
		synchronized (encoderPositionChangeListeners) {
			encoderPositionChangeListeners.remove(l);
			enableEncoderPositionChangeEvents(encoderPositionChangeListeners.size() > 0);
		}
	}
	private void fireEncoderPositionChange(EncoderPositionChangeEvent e) {
		synchronized (encoderPositionChangeListeners) {
			for (Iterator it = encoderPositionChangeListeners.iterator(); it.hasNext(); )
				((EncoderPositionChangeListener)it.next()).encoderPositionChanged(e);
		}
	}
	private native void enableEncoderPositionChangeEvents(boolean b);
	private LinkedList inputChangeListeners = new LinkedList();
	private long nativeInputChangeHandler = 0;
	public final void addInputChangeListener(InputChangeListener l) {
		synchronized (inputChangeListeners) {
			inputChangeListeners.add(l);
			enableInputChangeEvents(true);
		}
	}
	public final void removeInputChangeListener(InputChangeListener l) {
		synchronized (inputChangeListeners) {
			inputChangeListeners.remove(l);
			enableInputChangeEvents(inputChangeListeners.size() > 0);
		}
	}
	private void fireInputChange(InputChangeEvent e) {
		synchronized (inputChangeListeners) {
			for (Iterator it = inputChangeListeners.iterator(); it.hasNext(); )
				((InputChangeListener)it.next()).inputChanged(e);
		}
	}
	private native void enableInputChangeEvents(boolean b);
}
