package unifm;


import com.one.Accelerometer;

//#if JSR256 == "true"

import com.vmx.AuxClass;
import javax.microedition.sensor.*;
import javax.microedition.io.Connector;
import java.io.IOException;

public class AccelImpl implements Accelerometer
{
    protected int[] channels = new int[3];
    protected String[] channelNames = new String[3];
    protected SensorConnection sensor;
    
	public AccelImpl() throws ClassNotFoundException, IOException
	{
		if(!AuxClass.classExists("javax.microedition.sensor.SensorConnection"))
		{
			throw new ClassNotFoundException();
		}

        SensorInfo[] info = SensorManager.findSensors("acceleration", null);
		ChannelInfo[] ci = info[0].getChannelInfos();

		for(int r = 0; r < ci.length; r++)
		{
			channelNames[r] = ci[r].getName();
		}

		sensor = (SensorConnection)Connector.open(info[0].getUrl());

        if(sensor == null)
        {
        	throw new ClassNotFoundException();
        }
	}

	public int getValue(int channel)
	{
		getDelta(channel, 0);
		return channels[channel];
	}
	
	public int getDelta(int channel, int threshold)
	{
		int delta = 0;
		
		try
		{
			Data[] data = sensor.getData(1, -1, false, false, false);
			int drx = 0;

			for(int i = 0; i < data.length; i++)
			{
				if(data[i].getChannelInfo().getName().equals(channelNames[channel]))
				{
					drx = data[i].getIntValues()[0];
				}
			}

			delta = channels[channel] - drx;
			channels[channel] = drx;

			if(Math.abs(delta) < threshold)
			{
				delta = 0;
			}
		}
		catch(Throwable t)
		{
		}
		
		return delta;
	}
}

//#else
//#
//# public class AccelImpl implements Accelerometer
//# {
//# 	public int getValue( int channel)
//# 	{
//# 		return 0;
//# 	}
//#
//# 	public int getDelta(int channel, int threshold)
//# 	{
//# 		return 0;
//# 	}
//# }
//#
//#endif