package com.eni.android.sensor;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class SensorActivity extends Activity {

	private int sensorType = Sensor.TYPE_MAGNETIC_FIELD;

	private TextView xTextView;
	private TextView yTextView;
	private TextView zTextView;
	private TextView magneticValueTextView;

	private float xAxis = 0f;
	private float yAxis = 0f;
	private float zAxis = 0f;
	private double magneticValues;

	private final SensorEventListener magneticEventListener = new SensorEventListener() {
		@Override
		public void onSensorChanged(SensorEvent event) {
			if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
				xAxis = event.values[0];
				yAxis = event.values[1];
				zAxis = event.values[2];
				
				magneticValues = android.util.FloatMath.sqrt((xAxis * xAxis
						+ yAxis * yAxis + zAxis * zAxis));
				xTextView.setText("Axe x = " + Float.toString(xAxis));
				yTextView.setText("Axe y = " + Float.toString(yAxis));
				zTextView.setText("Axe z = " + Float.toString(zAxis));
				magneticValueTextView.setText("Valeur du champ magnetique = " + magneticValues);
			}
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.accelerometre);

		xTextView = (TextView) findViewById(R.id.x_axis);
		yTextView = (TextView) findViewById(R.id.y_axis);
		zTextView = (TextView) findViewById(R.id.z_axis);
		magneticValueTextView = (TextView) findViewById(R.id.magnetic_value);

		final SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		sensorManager.registerListener(magneticEventListener,
				sensorManager.getDefaultSensor(sensorType),
				SensorManager.SENSOR_DELAY_NORMAL);
	}
}
