package chromaticTuner.tuner;
import com.example.tradhero.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class InputVolumeCalibrationActivity extends Activity {
	
	private Recorder m_recorder= null;
	private InputVolumeCalibrationActivity m_activity = null;
	private RmsMeasurer m_rmsMeasurer = null;
	private final int AUDIO_RECORDING_ERROR = 1;
	
	// time to measure in seconds
	private float m_measurementLength = 5.0f;
	private float m_measuredLength = 0.0f;
	private double m_highestMeasurement = 0.0;
	private double m_lowestMeasurement = 0.0;
	private double m_measuredVolume = 0.0;
	private double m_measuredVolumeMargin = 3.0;
	
	private double m_latestRms = 0.0;
	private double m_initThreshold = 6.0;
	
	private boolean m_success = false;
	private boolean m_stopped = true;
	
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.input_volume_calibration);
        m_recorder = new Recorder();
        m_recorder.setOnAudioBufferListener(m_audioBufferListener);
        m_recorder.setOnAudioRecorderInitializeError(m_audioRecorderInitializeError);
        m_rmsMeasurer = new RmsMeasurer();
        m_activity = this;
        
        Button restartButton = (Button)findViewById(R.id.calibration_restart);
		restartButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				stop();
				start();
			}
		});
    }
    
    public void onResume()
    {
    	super.onResume();
		stop();
		start();
    }
    
    public void onPause()
    {
    	super.onPause();
    	stop();
    	if (m_success)
    	{ 		
    		String value = String.valueOf( ((int)(m_measuredVolume*10)) /10.0  );
    		SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
    		editor.putString(SettingsActivity.OPTION_VOLUME_THRESHOLD, value);
    		editor.commit();
    	}
    }
    
	public Dialog onCreateDialog(int id)
	{
		// only audio recording error
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Failed to start recording audio. Application will quit.")
		       .setCancelable(false)
		       .setPositiveButton("Quit", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                InputVolumeCalibrationActivity.this.finish();
		           }
		       });
		AlertDialog alert = builder.create();
		return alert;
	}
	
	private OnAudioBufferListener m_audioBufferListener = new OnAudioBufferListener() {
		public void onAudioBuffer(short[] buffer) {
			
			if (m_stopped)
			{
				return;
			}
			
			m_latestRms = m_rmsMeasurer.measureRms(buffer);
			if (m_latestRms<m_lowestMeasurement)
			{
				m_lowestMeasurement=m_latestRms;
			}
			if (m_latestRms>m_highestMeasurement)
			{
				m_highestMeasurement=m_latestRms;
			}
			
			if (Math.abs(m_lowestMeasurement-m_highestMeasurement)>m_initThreshold)
			{
				initializeMeasurement();
			}
			else
			{
				m_measuredLength+=buffer.length/(double)m_recorder.getSampleRate();
			}
			
			if (m_measuredLength>m_measurementLength)
			{
				m_measuredLength=m_measurementLength;
				m_success=true;
				m_activity.runOnUiThread(new Runnable() {
				    public void run() {
				    	stop();
				    	TextView view = (TextView)findViewById(R.id.info_text_view);
						view.setText("Done. Tap back or restart.");
				    }
				  });
			}
			
			m_measuredVolume=Math.floor(m_highestMeasurement+m_measuredVolumeMargin+1.0);
			
			m_activity.runOnUiThread(new Runnable() {
			    public void run() {
			    	TextView view = (TextView)findViewById(R.id.progress_view);
			    	if (m_measuredLength<m_measurementLength)
			    	{
			    		view.setText("Progress: " + (int)(m_measuredLength/m_measurementLength*100.0) + " %");	
			    	}
			    	else
			    	{
			    		view.setText("");
			    	}
			    }
			  });
			m_activity.runOnUiThread(new Runnable() {
			    public void run() {
			    	TextView view = (TextView)findViewById(R.id.rms_view);
					view.setText("Input volume level: " + m_measuredVolume + " dB");
			    }
			  });
		}
	};
	
	public OnAudioRecorderInitializeErrorListener m_audioRecorderInitializeError = new OnAudioRecorderInitializeErrorListener() {
		public void audioRecorderInitializeError() {
			m_activity.runOnUiThread(new Runnable() {
			    public void run() {
			    	m_activity.showDialog(m_activity.AUDIO_RECORDING_ERROR);
			    }
			  });
		}
	};
	
	private void initializeMeasurement()
	{
		m_measuredLength=0.0f;
		m_lowestMeasurement=0.0f;
		m_highestMeasurement=-120.0f;
		m_success=false;
		m_activity.runOnUiThread(new Runnable() {
		    public void run() {
				TextView view = (TextView)findViewById(R.id.info_text_view);
				view.setText("Silence, please. Measuring background noise.");
		    }
		});
	}

	private void start()
	{
		m_stopped=false;
		initializeMeasurement();
		m_recorder.start();
	}
	
	private void stop()
	{
		m_stopped=true;
		m_recorder.stop();
	}
}
