package com.appli.gui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import android.widget.CompoundButton.OnCheckedChangeListener;

import com.appli.patoche.R;


//http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/
//https://examples.javacodegeeks.com/android/android-mediaplayer-example/

public class player_activity extends Activity{
	
	
		private MediaPlayer mediaPlayer;
		public TextView songName, duration, timer;
		private double timeElapsed = 0, finalTime = 0;
		private int forwardTime = 2000, backwardTime = 2000;
		private Handler durationHandler = new Handler();
		private SeekBar seekbar;
		private String mp3;
		private Switch btn_mute;
		private int currentSongIndex = 0;
		private ArrayList<String> songsList; 
		private Handler Handler_timer = new Handler();
		private Utilities utils;
		private int seekForwardTime = 5000; // 5000 milliseconds
	    private int seekBackwardTime = 5000; // 5000 milliseconds
	
		public void onCreate(Bundle savedInstanceState)
	    {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.player);
	        Intent id = getIntent();  
	        songsList = id.getStringArrayListExtra("key");
			songName = (TextView) findViewById(R.id.songName);
			seekbar = (SeekBar) findViewById(R.id.seekBar);
			duration = (TextView) findViewById(R.id.duration);
			timer = (TextView) findViewById(R.id.timer);
			
			

			utils = new Utilities();
			
	        //initializeViews();
	        playSong(0);
	        
	        control_volume();
	        
	        btn_mute = (Switch) findViewById(R.id.btn_mute);
	        // etat par defaut
	        btn_mute.setChecked(false);
	        
	        
	        seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() 
	        {
		  		  int progress = 0;
		  		  
		  		  @Override
		  		  public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser)
		  		  {
		  			 
		  		  }
		  		
		  		  @Override
		  		  public void onStartTrackingTouch(SeekBar seekBar) 
		  		  {
		  			  Handler_timer.removeCallbacks(mUpdateTimeTask);
		  		  }
		  		
		  		  @Override
		  		  public void onStopTrackingTouch(SeekBar seekBar) 
		  		  {
		  			  Handler_timer.removeCallbacks(mUpdateTimeTask);
		  			  int totalDuration = mediaPlayer.getDuration();
		  			  int currentPosition = utils.progressToTimer(seekbar.getProgress(), totalDuration);
		  	 
		  			  // 	forward or backward to certain seconds
		  			  mediaPlayer.seekTo(currentPosition);
		  	 
		  			  // update timer progress again
		  			  updateProgressBar();
		  		  }
	  	   });
	  	 
	        
	        btn_mute.setOnCheckedChangeListener(new OnCheckedChangeListener() 
	        {
		         @Override
		         public void onCheckedChanged(CompoundButton buttonView,  boolean isChecked) 
		         {
		        	 if(isChecked)
		        	 {
		        		 //switchStatus.setText("Switch is currently ON");
		        		 AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
		        		 amanager.setStreamMute(AudioManager.STREAM_MUSIC, true);
		        		 Toast.makeText(getApplicationContext(), "ON", Toast.LENGTH_SHORT).show();
		        	 }
		        	 else
		        	 {
		        		 // switchStatus.setText("Switch is currently OFF");
		        		 AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
		        		 amanager.setStreamMute(AudioManager.STREAM_MUSIC, false);
		        		 Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT).show();
		        	 }
	
		         }
		         	         
	        });
	        
	        
	        mediaPlayer.setOnCompletionListener(new OnCompletionListener() 
	        {           
	            public void onCompletion(MediaPlayer mp)
	            {          
	            	
	            	if(currentSongIndex < (songsList.size() - 1))
	            	{
	 	                mp.stop();
	 	                mp.reset();
	 	                String element = songsList.get(currentSongIndex + 1);
  	 	                String titre = "/sdcard/" + element;
	 	                currentSongIndex = currentSongIndex + 1;
	 	                songName.setText(element);
	 	               
	 	                try {
	 	                		mp.setDataSource(titre);
	 	                		mp.prepare();
	 	                		mp.start();
						} 
	 	                catch (IOException e) 
	 	                {
	 	                		e.printStackTrace();
						}
	 	               updateProgressBar();
	                  
	                }
	            	
	            	else
	            	{
	                    // bouclage 
	            		mp.stop();
	 	                mp.reset();
	 	                currentSongIndex = 0;
	 	                String element = songsList.get(currentSongIndex);
	 	                String titre = "/sdcard/" + element;
	 	                songName.setText(element);
	 	               
	 	                try 
	 	                {
	 	                		mp.setDataSource(titre);
	 	                		mp.prepare();
	 	                		mp.start();
						} 
	 	                
	 	                catch (IOException e)
	 	                {
							e.printStackTrace();
						}
	 	              
	                }
	            	
	               
	            }
	        });
	    
	        
	        
	    }    

	        public void  playSong(int songIndex)
	        {
		            	//mediaPlayer.reset();
	        			//mediaPlayer.stop();
	        	//if(mediaPlayer.isPlaying())
        		
	        	 if(mediaPlayer != null)
	        	 {
	        		mediaPlayer.stop();
	        	 }
		            	mp3 = songsList.get(songIndex); 
		    			songName.setText(mp3);
		    			String chemin = "file:///sdcard/" + mp3 ;
		    		    Uri myUri = Uri.parse(chemin);
		    		    mediaPlayer = MediaPlayer.create(this, myUri);
		                seekbar.setProgress(0);
		                seekbar.setMax(100);
		    		    mediaPlayer.start();
		                updateProgressBar();
	        }   
	        
	        
	        
	        public void updateProgressBar()
		    {
		        Handler_timer.postDelayed(mUpdateTimeTask, 100);
		    }   
		    
	        private Runnable mUpdateTimeTask = new Runnable()
		    {
		           public void run()
		           {
		               long totalDuration = mediaPlayer.getDuration();
		               long currentDuration = mediaPlayer.getCurrentPosition();
		 
		               duration.setText(""+utils.milliSecondsToTimer(totalDuration));
		               timer.setText(""+utils.milliSecondsToTimer(currentDuration));
		               seekbar.setMax((int) totalDuration);
		   			   seekbar.setProgress((int) currentDuration);
		               Handler_timer.postDelayed(this, 100);
		   			   
		               // Updating progress bar
		               //int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
		               //Log.d("Progress", ""+progress);
		               //seekbar.setProgress(progress);
		 
		           }
		        };
	        
	        public void initializeViews()
	        {
				 	mp3 = songsList.get(currentSongIndex); 
					songName.setText(mp3);
					String chemin = "file:///sdcard/" + mp3 ;
				    Uri myUri = Uri.parse(chemin);
				    mediaPlayer = MediaPlayer.create(this, myUri);
				    
					finalTime = mediaPlayer.getDuration();
					duration = (TextView) findViewById(R.id.duration);
					timer = (TextView) findViewById(R.id.timer);
					seekbar.setMax((int) finalTime);
					seekbar.setClickable(false);
					duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))));
		
					//	seekbar.setProgress(0);
					//	seekbar.setMax(100);
	        } 

		public void play(View view) 
		{
			mediaPlayer.start();
			updateProgressBar();
		//	timeElapsed = mediaPlayer.getCurrentPosition();
		//	seekbar.setProgress((int) timeElapsed);
		//	durationHandler.postDelayed(updateSeekBarTime, 100);
		}

		//handler to change seekBarTime
		private Runnable updateSeekBarTime = new Runnable() 
		{
			public void run() {
				//get current position
				timeElapsed = mediaPlayer.getCurrentPosition();
				//set seekbar progress
				seekbar.setProgress((int) timeElapsed);
				//set time remaing
				double timeRemaining = finalTime - timeElapsed;
				//duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
				
				timer.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeElapsed), TimeUnit.MILLISECONDS.toSeconds((long) timeElapsed) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeElapsed))));
				duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))));
				
				//repeat yourself that again in 100 miliseconds
				durationHandler.postDelayed(this, 100);
			}
		};

		// pause mp3 song
		public void pause(View view) 
		{
			mediaPlayer.pause();
		}

		// go forward at forwardTime seconds
		public void forward(View view)
		{
			//check if we can go forward at forwardTime seconds before song endes
/*			if ((timeElapsed + forwardTime) <= finalTime) 
			{
				timeElapsed = timeElapsed + forwardTime;

				//seek to the exact second of the track
				mediaPlayer.seekTo((int) timeElapsed);
			}
*/			
			
			int currentPosition = mediaPlayer.getCurrentPosition();
            // check if seekForward time is lesser than song duration
            if(currentPosition + seekForwardTime <= mediaPlayer.getDuration())
            {
                // forward song
            	mediaPlayer.seekTo(currentPosition + seekForwardTime);
            }
            else
            {
                // forward to end position
            	mediaPlayer.seekTo(mediaPlayer.getDuration());
            }
			
		}

		// go backwards at backwardTime seconds
		public void rewind(View view) 
		{
			//check if we can go back at backwardTime seconds after song starts
			/*if ((timeElapsed - backwardTime) > 0) {
				timeElapsed = timeElapsed - backwardTime;
				
				//seek to the exact second of the track
				mediaPlayer.seekTo((int) timeElapsed);
			}*/
			
			int currentPosition = mediaPlayer.getCurrentPosition();
            // check if seekBackward time is greater than 0 sec
            if(currentPosition - seekBackwardTime >= 0)
            {
                // forward song
            	mediaPlayer.seekTo(currentPosition - seekBackwardTime);
            }
            else
            {
                // backward to starting position
            	mediaPlayer.seekTo(0);
            }
		}
		
		
		public void next(View view) 
		{
		    
			/*mediaPlayer.stop();
			currentSongIndex = currentSongIndex + 1 ;
            String element = songsList.get(currentSongIndex);
            String titre = "/sdcard/" + element;
            songName.setText(element);*/
            
            
            if(currentSongIndex < (songsList.size() - 1))
            {
                playSong(currentSongIndex + 1);
                currentSongIndex = currentSongIndex + 1;
            }
            else
            {
                // play first song
                playSong(0);
                currentSongIndex = 0;
            }

		}
		
		
		public void previous(View view) 
		{
			 if(currentSongIndex > 0)
			 {
                 playSong(currentSongIndex - 1);
                 currentSongIndex = currentSongIndex - 1;
             }
			 else{
                 // play last song
                 playSong(songsList.size() - 1);
                 currentSongIndex = songsList.size() - 1;
             }
			
		}
		 
	    public void control_volume()
	    {
	        try
	        {
	        	SeekBar volume = (SeekBar)findViewById(R.id.bar_volume);
	        	final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
	        	volume.setMax(audioManager
	                    .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
	        	volume.setProgress(audioManager
	                    .getStreamVolume(AudioManager.STREAM_MUSIC));   


	            volume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() 
	            {
	                public void onStopTrackingTouch(SeekBar arg0) 
	                {
	                }

	                public void onStartTrackingTouch(SeekBar arg0) 
	                {
	                }

	                public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) 
	                {
	                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
	                }
	            });
	        }
	        catch (Exception e) 
	        {
	            e.printStackTrace();
	        }
	    }
	    
	    
	    
	    
}


class Utilities {
	 
    /**
     * Function to convert milliseconds time to
     * Timer Format
     * Hours:Minutes:Seconds
     * */
    public String milliSecondsToTimer(long milliseconds)
    {
        String finalTimerString = "";
        String secondsString = "";
 
        // Convert total duration into time
           int hours = (int)( milliseconds / (1000*60*60));
           int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
           int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
           // Add hours if there
           if(hours > 0){
               finalTimerString = hours + ":";
           }
 
           // Prepending 0 to seconds if it is one digit
           if(seconds < 10){
               secondsString = "0" + seconds;
           }else{
               secondsString = "" + seconds;}
 
           finalTimerString = finalTimerString + minutes + ":" + secondsString;
 
        // return timer string
        return finalTimerString;
    }
 
    /**
     * Function to get Progress percentage
     * @param currentDuration
     * @param totalDuration
     * */
    public int getProgressPercentage(long currentDuration, long totalDuration){
        Double percentage = (double) 0;
 
        long currentSeconds = (int) (currentDuration / 1000);
        long totalSeconds = (int) (totalDuration / 1000);
 
        // calculating percentage
        percentage =(((double)currentSeconds)/totalSeconds)*100;
 
        // return percentage
        return percentage.intValue();
    }
 
    /**
     * Function to change progress to timer
     * @param progress -
     * @param totalDuration
     * returns current duration in milliseconds
     * */
    public int progressToTimer(int progress, int totalDuration) {
        int currentDuration = 0;
        totalDuration = (int) (totalDuration / 1000);
        currentDuration = (int) ((((double)progress) / 100) * totalDuration);
 
        // return current duration in milliseconds
        return currentDuration * 1000;
    }
}
