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.view.Menu;
import android.widget.TextView;

public class SensorMagneticoActivity 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 = java.lang.Math.sqrt((xAxis * xAxis
						+ yAxis * yAxis + zAxis * zAxis));
				xTextView.setText("Eje x = " + Float.toString(xAxis));
				yTextView.setText("Eje y = " + Float.toString(yAxis));
				zTextView.setText("Eje z = " + Float.toString(zAxis));
				magneticValueTextView.setText("Valor del campo magnético = " + magneticValues);
			}
		}

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

		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		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);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.sensor_magnetico, menu);
		return true;
	}

}
