package com.example.recorder02;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Chronometer;

public class MainActivity extends Activity 
{

   private MediaRecorder myRecorder;
   private MediaPlayer myPlayer;
   private String outputFile = null;
   private Button startBtn;
   private Button stopBtn;
   private Button playBtn;
   private Button stopPlayBtn;
   private TextView text;
   TextView textTimer;
   
   private long startTime = 0L;
   private Handler myHandler = new Handler();
   long timeInMilliseconds = 0L;
   long timeSwapBuff = 0L;
   long updatedTime = 0L;
   
   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
		      super.onCreate(savedInstanceState);
		      setContentView(R.layout.activity_main);
		      
		      textTimer = (TextView) findViewById(R.id.textTimer);
		     
		      //outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/javacodegeeksRecording.3gpp";
		      //myRecorder = new MediaRecorder();
		      //myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		      //myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		      //myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
		      //myRecorder.setOutputFile(outputFile);
		      /*
		      final Runnable hMyTimeTask = new Runnable()
		      {
				   	   public void run() 
				   	   {
				   		   nCounter++;
				   		textTimer.setText("Hallo from thread counter: " + nCounter);
				   	   }
		      }; 
		      */
		      
		      /**/
		      startBtn = (Button)findViewById(R.id.start);
		      startBtn.setOnClickListener(new OnClickListener()
		      {
		    	  @Override
		    	  public void onClick(View v)
		    	  {
					//start(v);
		    		  //((Chronometer) findViewById(R.id.chronometer)).start();
		    		  //Toast.makeText(getApplicationContext(), "un...", Toast.LENGTH_SHORT).show();
		    		  // myHandler.removeCallbacks(hMyTimeTask);
		    	      // myHandler.postDelayed(hMyTimeTask, 1000); // delay 1 second
		    		  startTime = SystemClock.uptimeMillis();
		    		  myHandler.postDelayed(updateTimerThread, 0);
		    		  stopBtn.setEnabled(true);
		    		  startBtn.setEnabled(false);
		    	  }
		      });
		      
		      // pour le stop 
		      //((Chronometer) findViewById(R.id.chronometer)).stop();
		      
		      // pour le reset 
		      //((Chronometer) findViewById(R.id.chronometer)).setBase(SystemClock.elapsedRealtime());
		      
		      /**/
		      stopBtn = (Button)findViewById(R.id.stop);
		      stopBtn.setOnClickListener(new OnClickListener() 
		      {
		    	  @Override
		  			public void onClick(View v)
		    	  	{
		    		  //stop(v);
		    		  timeSwapBuff += timeInMilliseconds;
		    		  myHandler.removeCallbacks(updateTimerThread);
		    		  stopBtn.setEnabled(false);
		    		  startBtn.setEnabled(true);
		    		  //Toast.makeText(getApplicationContext(), "Deux...", Toast.LENGTH_SHORT).show();
		    	  	}
		      });
		
		      /**/
		      
		      playBtn = (Button)findViewById(R.id.play);
		      playBtn.setOnClickListener(new OnClickListener() 
		      {
		  			@Override
		  			public void onClick(View v)
		  			{
						//play(v);	
		  			     //startTime = SystemClock.uptimeMillis();
		  			     //myHandler.postDelayed(updateTimerMethod, 0);
		  				 Toast.makeText(getApplicationContext(), "Trois...", Toast.LENGTH_SHORT).show();
		  			}
		      });
		      
		      /**/
		      
		      stopPlayBtn = (Button)findViewById(R.id.stopPlay);
		      stopPlayBtn.setOnClickListener(new OnClickListener() 
		      {
		    	  	@Override
		  			public void onClick(View v)
		    	  	{
		    	  		//stopPlay(v);
		    	  	    // timeSwap += timeInMillies;
		    	  	    //myHandler.removeCallbacks(updateTimerMethod);
		    	  		 Toast.makeText(getApplicationContext(), "Quatre...", Toast.LENGTH_SHORT).show();
		    	  	}
		      });
   }

   public void start(View view)
   {
	   try 
	   {
          myRecorder.prepare();
          myRecorder.start();
       } 
	   catch (IllegalStateException e)
	   {
          // start:it is called before prepare()
    	  // prepare: it is called after start() or before setOutputFormat() 
          e.printStackTrace();
       } 
	   catch (IOException e)
	   {
           // prepare() fails
           e.printStackTrace();
       }
	   
       text.setText("Recording Point: Recording");
       startBtn.setEnabled(false);
       stopBtn.setEnabled(true);
       Toast.makeText(getApplicationContext(), "Start recording...", Toast.LENGTH_SHORT).show();
   }

   public void stop(View view)
   {
	   try 
	   {
	      myRecorder.stop();
	      myRecorder.release();
	      myRecorder  = null;
	      
	      stopBtn.setEnabled(false);
	      playBtn.setEnabled(true);
	      text.setText("Recording Point: Stop recording");
	      Toast.makeText(getApplicationContext(), "Stop recording...",  Toast.LENGTH_SHORT).show();
	   } 
	   catch (IllegalStateException e)
	   {
			//  it is called before start()
			e.printStackTrace();
	   } 
	   catch (RuntimeException e)
	   {
			// no valid audio/video data has been received
			e.printStackTrace();
	   }
   }
  
   public void play(View view) 
   {
	   try
	   {
		   myPlayer = new MediaPlayer();
		   myPlayer.setDataSource(outputFile);
		   myPlayer.prepare();
		   myPlayer.start();
		   
		   playBtn.setEnabled(false);
		   stopPlayBtn.setEnabled(true);
		   text.setText("Recording Point: Playing");
		   
		   Toast.makeText(getApplicationContext(), "Start play the recording...", Toast.LENGTH_SHORT).show();
	   } 
	   catch (Exception e) 
	   {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
   }
   
   public void stopPlay(View view)
   {
	   try 
	   {
	       if (myPlayer != null) 
	       {
	    	   myPlayer.stop();
	           myPlayer.release();
	           myPlayer = null;
	           playBtn.setEnabled(true);
	           stopPlayBtn.setEnabled(false);
	           text.setText("Recording Point: Stop playing");
	           Toast.makeText(getApplicationContext(), "Stop playing the recording...",  Toast.LENGTH_SHORT).show();
	       }
	   }
	   catch (Exception e)
	   {
			// TODO Auto-generated catch block
			e.printStackTrace();
	   }
   }
   
   
   private Runnable updateTimerThread = new Runnable() {

		public void run() {
			
			timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
			
			updatedTime = timeSwapBuff + timeInMilliseconds;

			int secs = (int) (updatedTime / 1000);
			int mins = secs / 60;
			secs = secs % 60;
			int milliseconds = (int) (updatedTime % 1000);
			textTimer.setText("" + mins + ":"
					+ String.format("%02d", secs) + ":"
					+ String.format("%03d", milliseconds));
			myHandler.postDelayed(this, 0);
		}

	};
	
	
	private File getOutputFile()
	{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.US);
        return new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()
                + "/Voice Recorder/RECORDING_" + dateFormat.format(new Date()) + ".m4a");
    }
	// PCM  ou AMR
	// sample rate 44100
	// https://gist.github.com/chathudan/95d9acdd741b2a577483
	
	// mRecorder.setAudioEncodingBitRate(64000)
	//  mRecorder.setAudioSamplingRate(16000);
	
	// String str = Environment.getExternalStorageDirectory().getAbsolutePath();
    // recorder.setOutputFile(str + "/" + System.currentTimeMillis() + ".mp3");
    
    // <uses-permission android:name="android.permission.RECORD_AUDIO" />
    // <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
	
	// recorder = new MediaRecorder();
	// recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
	// recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);  pour le format MP3
	// recorder.setOutputFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/myrecording.mp3");
	     // recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
	     // recorder.prepare();
	     // recorder.start();
	

	//   lecteur audio            https://examples.javacodegeeks.com/android/android-mediaplayer-example/
	/*
	MediaPlayer mp=new MediaPlayer();  
    try{  
        mp.setDataSource("/sdcard/Music/maine.mp3");//Write your location here  
        mp.prepare();  
        mp.start();  
          
    }catch(Exception e){e.printStackTrace();}  
	 */
}

