package com.tryandroid.sensor;


import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public abstract class BaseSensorEventListener implements SensorEventListener {
	public static final int NO_FILTER = 0;
	public static final int LOW_PASS_FILTER = 1;
	public static final int HIGH_PASS_FILTER = 2;

	protected ValueHolder xValues;
	protected ValueHolder yValues;
	protected ValueHolder zValues;

	private SensorActivity activity;
	private int filterId = NO_FILTER;

	public BaseSensorEventListener(SensorActivity activity, int count) {
		this.activity = activity;
		xValues = new ValueHolder(count);
		yValues = new ValueHolder(count);
		zValues = new ValueHolder(count);
	}

	/**
	 * 精度が変更された時のイベント
	 */
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		Log.d(getClass().getName(), "onAccuracyChanged Called");
	}

	/**
	 * 測定値に変更があった時のイベント
	 */
	@Override
	public void onSensorChanged(SensorEvent event) {
		Log.d(getClass().getName(), "onSensorChanged Called");
		xValues.add(event.values[SensorManager.DATA_X]);
		yValues.add(event.values[SensorManager.DATA_Y]);
		zValues.add(event.values[SensorManager.DATA_Z]);
		activity.update();
	}

	/**
	 * フィルタの設定
	 *
	 * @param filterId
	 */
	public void setFilter(int filterId) {
		this.filterId = filterId;
	}

	protected String getXValueString() {
		return getValueString(xValues);
	}

	protected String getYValueString() {
		return getValueString(yValues);
	}

	protected String getZValueString() {
		return getValueString(zValues);
	}

	protected String getValueString(ValueHolder values) {
		return String.valueOf(getValue(values));
	}

	/**
	 * 測定値の取得
	 *
	 * @param values
	 * @return 測定値
	 */
	protected float getValue(ValueHolder values) {
		float value = 0;
		switch (filterId) {
		// ローパスフィルタ
		case LOW_PASS_FILTER:
			value = values.getMedian();
			break;
		// ハイパスフィルタ
		case HIGH_PASS_FILTER:
			value = values.getValue() - values.getMedian();
			break;
		// フィルタなし
		default:
			value = values.getValue();
			break;
		}
		return value;
	}

	public abstract String getName();

	public abstract String getResult();
}
