package akshay.is.awesome;

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

public class Pendulum extends Activity implements SensorEventListener{

	TextView [] t = new TextView[7];
	double period = 0, length, avgp, totalp, avgl, totall;
	long time;
	boolean swich, swich2, swich3=false;
	int swipez=-1;
	//ArrayList<Double> avgper = new ArrayList<Double>();
	//ArrayList<Double> avglen = new ArrayList<Double>();
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
              
        getWindow().getDecorView().findViewById(android.R.id.content).setKeepScreenOn(true);
        
        t[0] = (TextView)findViewById(R.id.TextView01);
        t[1] = (TextView)findViewById(R.id.TextView02);
        t[2] = (TextView)findViewById(R.id.TextView03);
        t[3] = (TextView)findViewById(R.id.TextView04);
        t[4] = (TextView)findViewById(R.id.TextView05);
        //t[5] = (TextView)findViewById(R.id.TextView06);
        //t[6] = (TextView)findViewById(R.id.TextView07);
        
		SensorManager m = (SensorManager) this.getBaseContext().getSystemService(Context.SENSOR_SERVICE);
		Sensor s = m.getDefaultSensor(Sensor.TYPE_PROXIMITY);
		m.registerListener((SensorEventListener) this, s, SensorManager.SENSOR_DELAY_FASTEST);
    }

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

	@Override
	public void onSensorChanged(SensorEvent event) {
		if(event.values[0]==1){
			swipez++;
			if(!swich){
				time = System.currentTimeMillis();
				swich=true;
			}else
				swich2=true;
		}else {
			if(swich2)
				swich=false;
			if(!swich) {
				period = (System.currentTimeMillis()-time)/1000.0;
				length = (period/(2*Math.PI))*(period/(2*Math.PI))*9.81;
				//avgper.add(period);
				//avglen.add(length);
				swich2=false;
				t[0].setText("Period: "+period+"s");
				t[1].setText("Frequency: "+ 1/period+ "Hz");
				t[2].setText("Angular Velocity: " + (2*Math.PI)/period + "rad/s");
				t[3].setText("Length: " + length + "m");
				/*for(int x=0;x<avgper.size();x++) {
					totalp+=avgper.get(x);
					totall+=avglen.get(x);
				}
				t[5].setText("Avg. Period: " + totalp/avgper.size() + "s");
				t[6].setText("Avg. Length: " + totall/avglen.size() + "m");
				*/
			}
		}
		t[4].setText("Swipez: " + swipez);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add("Clear");
	    return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
			t[0].setText("Period:");
			t[1].setText("Frequency:");
			t[2].setText("Angular Velocity:");
			t[3].setText("Length:");
			t[4].setText("Swipez:");
			swipez=0;
			return super.onOptionsItemSelected(item);
	}
}