package com.example.utils01;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends Activity 
{

	 Button newButton,saveButton,openButton;
	 EditText text;
	
	/***************************************************/
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		newButton=(Button)findViewById(R.id.newButton);
        saveButton=(Button)findViewById(R.id.saveButton);
        openButton=(Button)findViewById(R.id.openButton);
        text=(EditText)findViewById(R.id.text);
	    
	    FileDemo instance = new FileDemo(this);
	    
	    // OK valide
//	    String lulu = instance.readFile("/sdcard/mysdfile.txt");
//	    Toast.makeText(getBaseContext(), lulu +"  OK  ", Toast.LENGTH_SHORT).show();
	    
	    // OK valide
//	    String text = instance.read("/sdcard/mysdfile.txt");
//	    Toast.makeText(getBaseContext(), text +" version 2  ", Toast.LENGTH_SHORT).show();
	    
	    // 
//	    ArrayList<String> myArr = instance.eadFile("/sdcard/mysdfile.txt");
//	    Toast.makeText(getBaseContext(), text +" version 3  ", Toast.LENGTH_SHORT).show();
	    
	    //
//	    List <String> FilesList;
//	    FilesList = instance.getSDFiles("/sdcard");
	    
	    // OK valide
//		instance.deleteFile("/sdcard/url.jpg");
	    
	    // OK valide
//	    instance.writeFile("/sdcard/dickou.txt", "abcdefghijklmnop"); 
	    
	    // OK valide
//	    instance.createDir("/sdcard/Perso");
	    
	    
	    //instance.copyFile("/mnt/sdcard/mysdfile.txt", "/mnt/sdcard/copie.txt");
	    
	    //instance.formatFileSize(46464646);
		
	}
	
	/***************************************************/
	 	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/***************************************************/
	 
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.

		switch (item.getItemId()) {
		case R.id.audio:
			Toast.makeText(getBaseContext(), "Item audio", Toast.LENGTH_SHORT).show();
    		Intent audio_Intent = new Intent(this,audio.class);
            startActivity(audio_Intent);
			break;

		
		case R.id.mp3:
			Toast.makeText(getBaseContext(), "Item audio", Toast.LENGTH_SHORT).show();
    		Intent mp3_Intent = new Intent(this,ListMp3_activity.class);
            startActivity(mp3_Intent);
			break;
	
		
		
		case R.id.add:
			Toast.makeText(getApplicationContext(), "You Clicked on Add",
					Toast.LENGTH_SHORT).show();
			break;
		case R.id.edit:
			Toast.makeText(getApplicationContext(), "You Clicked on Edit",
					Toast.LENGTH_SHORT).show();
			break;
		case R.id.share:
			Toast.makeText(getApplicationContext(),
					"You Clicked on Share, its menu inside a menu.",
					Toast.LENGTH_LONG).show();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	public void buttonAction(View v)
	{
        final EditText fileName=new EditText(this);
        AlertDialog.Builder ad=new AlertDialog.Builder(this);
        ad.setView(fileName);
 
        if (v.getId() == R.id.saveButton) 
        {
		            ad.setMessage("Save File");
		 
		            ad.setPositiveButton("Save",new DialogInterface.OnClickListener() 
		            {
		                @Override
		                public void onClick(DialogInterface dialog, int which)
		                {
		                    /*try
		                    {
		                        FileOutputStream fout=openFileOutput(fileName.getText().toString()+".txt",MODE_WORLD_READABLE);
		                        fout.write(text.getText().toString().getBytes());
		                    } 
		                    
		                    catch (Exception e) 
		                    {
		                        Toast.makeText(getApplicationContext(), "Error Occured: "+e,Toast.LENGTH_LONG).show();
		                    }*/
		                	
		                	try 
		                	{
		                		String path = "/mnt/sdcard/patoche/" + fileName.getText().toString()+".txt";
		                		FileDemo coco = new FileDemo(MainActivity.this);
		                		
		                		 coco.writeFile(path, text.getText().toString()); 
		                		
		                        //FileOutputStream fileout=openFileOutput(path, MODE_WORLD_WRITEABLE);
		                        //OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
		                        //outputWriter.write(text.getText().toString());
		                        //outputWriter.close();
		             
		                        //display file saved message
		                        Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_SHORT).show();
		             
		                    } 
		                	
		                	catch (Exception e) 
		                	{
		                        e.printStackTrace();
		                        Toast.makeText(getApplicationContext(), "Error Occured: "+e,Toast.LENGTH_LONG).show();
		                    }
		                	
		                }
		            });
		 
		            ad.setNegativeButton("Cancel",new DialogInterface.OnClickListener() 
		            {
		                @Override
		                public void onClick(DialogInterface dialog, int which) {
		                    dialog.cancel();
		                }
		            });
		 
		            ad.show();
 
        }
 
        if(v.getId()==R.id.openButton) 
        {
        	
        			Intent intent = new Intent(this, files_activity.class);
        			//startActivity(intent);
        			startActivityForResult(intent, 0);
        	  
		            /*
        			ad.setMessage("Open File");
		 
		            ad.setPositiveButton("Open",new DialogInterface.OnClickListener() 
		            {
		                @Override
		                public void onClick(DialogInterface dialog, int which) 
		                {
		 
		                    int c;
		                    text.setText("");
		 
		                    try 
		                    {
		                        FileInputStream fin = openFileInput(fileName.getText().toString()+".txt");
		 
		                        while ((c = fin.read()) != -1)
		                        {
		                            text.setText((text.getText().toString() + Character.toString((char) c)));
		                        }
		                    }
		                    
		                    catch (Exception e) 
		                    {
		                        Toast.makeText(getApplicationContext(), "Error Occured: "+e,Toast.LENGTH_LONG).show();
		                    }
		                }
		            });
		 
		            ad.setNegativeButton("Cancel",new DialogInterface.OnClickListener() 
		            {
		                @Override
		                public void onClick(DialogInterface dialog, int which) 
		                {
		                    dialog.cancel();
		                }
		            });
		 
		            ad.show();
		            */
		            
		           /* 
		            try {
		                FileInputStream fileIn=openFileInput("mytextfile.txt");
		                InputStreamReader InputRead= new InputStreamReader(fileIn);
		     
		                char[] inputBuffer= new char[READ_BLOCK_SIZE];
		                String s="";
		                int charRead;
		     
		                while ((charRead=InputRead.read(inputBuffer))>0) {
		                    // char to string conversion
		                    String readstring=String.copyValueOf(inputBuffer,0,charRead);
		                    s +=readstring;
		                }
		                InputRead.close();
		                textmsg.setText(s);
		                 
		     
		            } catch (Exception e) {
		                e.printStackTrace();
		            }
		            
		            */
		            
        }
 
        if(v.getId()==R.id.newButton) 
        {
        	int length = text.getText().toString().trim().length();
        	//String l = Integer.toString(length);
        	//Toast.makeText(this   , l ,   Toast.LENGTH_LONG).show();   
        	
        	if(length != 0)
        	{
        	
	        	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
	            alertDialogBuilder.setMessage("Confirmer Effacer");
	            
	            alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener()
	            {
	              @Override
	                public void onClick(DialogInterface arg0, int arg1)
	              	{
	            	  text.setText("");
	                  Toast.makeText(MainActivity.this,"Reset...",Toast.LENGTH_LONG).show();
	                  ActionBar ab = getActionBar();
	    			  ab.setTitle("Utils01");
	                }
	             });
	             
	             alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() 
	             {
		                @Override
		                public void onClick(DialogInterface dialog, int which) 
		                {
		                	dialog.cancel();
		                }
	             });
	             
	             AlertDialog alertDialog = alertDialogBuilder.create();
	             alertDialog.show();
        	}   
        	
        	else
        	{
        		//text.setText("");
        	}
            		
        }
    }
	
	@Override
    /*protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 
             if(resultCode == RESULT_OK){      
                // tvResult.setText(data.getIntExtra("result",-1)+"");          
             }
 
    }*/
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		 //Toast.makeText(this, "Retour du futur ...", Toast.LENGTH_SHORT).show();	
		
		  //if (resultCode == RESULT_OK && requestCode == 2) 
		  if(data != null && data.hasExtra("Order"))
		  {
			  Toast.makeText(this, data.getExtras().getString("Order"),     Toast.LENGTH_SHORT).show();
			  
			  String fichier = data.getExtras().getString("Order");
			  
			  FileDemo instance = new FileDemo(this);
			  
			  String contenu = instance.read("/sdcard/"+fichier);
			  text.setText(contenu);
			  
			  
			  ActionBar ab = getActionBar();
			  String titre = "Utils01:  " + fichier; 
			  ab.setTitle(titre);
		    /*if (data.hasExtra("returnKey1"))
		    {
		    	Toast.makeText(this, data.getExtras().getString("returnKey1"),     Toast.LENGTH_SHORT).show();
		    }*/
		  }
	} 


	
	
}


//////////////////////////////////////////////////

 class FileDemo 
 {
	 
	 Context c;
	
	 public FileDemo(Context context)
	 {
	     c= context;
	 }
	 
	 /***************************************************/
	 public String readFile(String filename)
	 {
	 
		 /*File file = new File(path);
		
		 try {
			 	BufferedReader br = new BufferedReader(new FileReader(file));
			 	String line;
			 	while ((line = br.readLine()) != null)
			 	{
			 		System.out.println(line);
			 	}
			 	br.close();
		 } 
		 
		 catch (IOException e) 
		 {
			// TODO Auto-generated catch block
			e.printStackTrace();
		 }
		 */
		 
		 //File path = new File("/mnt/sdcard/mysdfile.txt");
		 File qqpath = new File(filename);

		 try{
			 
		        // InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
		        //  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			 	BufferedReader bufferedReader = new BufferedReader(new FileReader(qqpath));
			 	String receiveString = "";
		        StringBuilder stringBuilder = new StringBuilder();

		        while ( (receiveString = bufferedReader.readLine()) != null )
		        {
		        	stringBuilder.append(receiveString);
		        }
		        
		        bufferedReader.close();
		        //inputStreamReader.close();
		        return stringBuilder.toString();
		 }
		 
		 catch (FileNotFoundException e) 
		 {   
		 } 
		 	
		 catch (IOException e) 
		 {
		 }	

		 return null;
		 
	 }	
	 
	 /***************************************************/
 
	 public ArrayList<String> eadFile(String filename)
	 {
		 	   //File pipo = new File("/mnt/sdcard/mysdfile.txt");
		 	  	File pipo = new File(filename);	
		 	   
			 	ArrayList<String> myArr = new ArrayList<String>();
				
				try {
						BufferedReader br = new BufferedReader(new FileReader(pipo));
						String line;
						
						while ((line = br.readLine()) != null)
						{
							myArr.add(line);
						}
						br.close();
				} 
				
				catch (IOException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return(myArr);
	 }
	 
	 /***************************************************/
	 
	 //https://www.learn2crack.com/2014/04/android-read-write-file.html
	 public String read(String fname)
	 {
		 
         BufferedReader br = null;
         String response = null;
 
            try {
 
	                StringBuffer output = new StringBuffer();
	                String fpath =  fname ;// "/sdcard/"+fname+".txt";
	 
	                br = new BufferedReader(new FileReader(fpath));
	                String line = "";
	                while ((line = br.readLine()) != null)
	                {
	                    output.append(line +"\n");
	                }
	                
	                br.close();
	                response = output.toString();
 
            } 
            
            catch (IOException e)
            {
                e.printStackTrace();
                return null;
            }
 
            return response;
 
     }
	 
	 /***************************************************/
	 public Boolean writeFile(String fname, String fcontent)
	 {
         try {

        	 	File file = new File(fname);

        	 	if (!file.exists())
        	 	{
        	 		file.createNewFile();
        	 	}

        	 	FileWriter fw = new FileWriter(file.getAbsoluteFile());
        	 	BufferedWriter bw = new BufferedWriter(fw);
        	 	bw.write(fcontent);
        	 	bw.close();
        		Toast.makeText(c   , "Ecriture OK",   Toast.LENGTH_LONG).show();   
        	 	
        	 	return true;

         } 
         
         catch (IOException e)
         {
             e.printStackTrace();
             return false;
         }

	 }
/***************************************************/
	 public List <String> getSDFiles(String path)
	 {
		  List <String> it = new ArrayList <String>();
		  File f = new File (path);
		  File[] files = f.listFiles ();
		  
		  for (int i = 0; i <files.length; i++)
		  {
		  		File  ptfile = files[i];
		  		Log.d("Count",ptfile.getPath());
		  		
		  		if(ptfile.isFile())
		  		{
		  			it.add (ptfile.getPath());
		  		}	
		  }
		  return it;
	 }
	 
	 /***************************************************/
	 public void deleteFile(String path)
	 {
		 try {
			
			 	File file = new File(path);
				if(file.exists())
				{
					file.delete();
				 	Toast.makeText(c   , "File Delete!",   Toast.LENGTH_LONG).show();   
				}
				file = null;
		 } 
		 
		 catch (Exception e)
		 {
			 e.printStackTrace();
			 Toast.makeText(c, "Failed! = " + e.getMessage() ,   Toast.LENGTH_LONG).show();   
		 }
	 }

	 /***************************************************/
	 public void createDir(String path)
	 {
		 try {
				File folder = new File(path);
				
				if(!folder.exists())
				{
					folder.mkdir();
				}
				
				folder = null;
				
	 		   	Toast.makeText(c, "Directory Create!", Toast.LENGTH_LONG).show();   
		 		   
		 } 
		 
		 catch (Exception e)
		 {
			 	e.printStackTrace();
			 	Toast.makeText(c, "Failed! = " + e.getMessage() , Toast.LENGTH_LONG).show();   
		 }
		 
	 }
	 
	 /***************************************************/
	 public void deleteDir(String path)
	 {
		 try {
				File folder = new File(path);
				
				if(!folder.exists())
				{
					folder.delete();
				}
				
				folder = null;
				
	 		   	Toast.makeText(c, "Directory delete!", Toast.LENGTH_LONG).show();   
		 		   
		 } 
		 
		 catch (Exception e)
		 {
			 	e.printStackTrace();
			 	Toast.makeText(c, "Failed! = " + e.getMessage() , Toast.LENGTH_LONG).show();   
		 }
		 
	 }
	 
	 /***************************************************/
	 
	 public void renameFile(String OldName, String NewName)
	 {
		 try {
				
				//String OldName = "/mnt/sdcard/mydata/myfile.txt";
				//String NewName = "/mnt/sdcard/mydata/myNewfile.txt";
				File file = new File(OldName);
				file.renameTo(new File(NewName));
				
				file = null;
			
	 		   	Toast.makeText(c, "File Rename!",  Toast.LENGTH_LONG).show();   
	 		   
		} 
		 
		catch (Exception e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
	 		Toast.makeText(c, "Failed! = " + e.getMessage() ,  Toast.LENGTH_LONG).show();   
		}
	 }
	 
	 /***************************************************/
	 
	 
	 private void copyFileUsingFileStreams(File source, File dest)
	 {
			InputStream input = null;
			OutputStream output = null;
			try {
				input = new FileInputStream(source);
				output = new FileOutputStream(dest);
				byte[] buf = new byte[1024];
				int bytesRead;
				while ((bytesRead = input.read(buf)) > 0)
				{
					output.write(buf, 0, bytesRead);
				}
				
				
				input.close();
				output.close();
			}
			catch (Exception e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
				Toast.makeText(c, "Failed! = " + e.getMessage() ,  Toast.LENGTH_LONG).show();   
			}
	 }
	 
	 /***************************************************/

	 
	 public void copyFile(String SourceName, String DestName)
	 {
		 try {
				
			 	File obj_SourceName = new File(SourceName);
				File obj_DestName = new File(DestName);
			 
				FileInputStream inStream = new FileInputStream(obj_SourceName);
			    FileOutputStream outStream = new FileOutputStream(obj_DestName);
			    FileChannel inChannel = inStream.getChannel();
			    FileChannel outChannel = outStream.getChannel();
			    inChannel.transferTo(0, inChannel.size(), outChannel);
			    inStream.close();
			    outStream.close();
			}
			 
			 
				//copyFile(SourceName,DestName); 
			
	 		   //	Toast.makeText(c, "File copied!",  Toast.LENGTH_LONG).show();   
	 		   	
	 		   	
	 		 //  	move
	 		/*   	
	 		   File SourceName = new File("/mnt/sdcard/mydata/myfile.txt");
	 		 
	 		  File DestName = new File("/mnt/sdcard/mypicture/myfile.txt");
	 		 
	 		  copyFile(SourceName,DestName); // Copy
	 		 
	 		  SourceName.delete(); // Delete
	 		   */
		 
		 
		catch (Exception e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
	 		Toast.makeText(c, "Failed! = " + e.getMessage() ,  Toast.LENGTH_LONG).show();   
		}
	 }
	 
	 
	 /***************************************************/
	 
	 
	 public void copyDirectory(File sourceLocation , File targetLocation) throws IOException 
	 {
			      
			     if (sourceLocation.isDirectory()) 
			     {
			         if (!targetLocation.exists()) 
			         {
			             targetLocation.mkdir();
			         }
			          
			         String[] children = sourceLocation.list();
			         for (int i=0; i<children.length; i++) 
			         {
			             	copyDirectory(new File(sourceLocation, children[i]),
			                new File(targetLocation, children[i]));
			         }
			     } 
			     
			     else
			     {
			          
			         InputStream in = new FileInputStream(sourceLocation);
			         OutputStream out = new FileOutputStream(targetLocation);
			          
			         // Copy the bits from instream to outstream
			         byte[] buf = new byte[1024];
			         int len;
			         while ((len = in.read(buf)) > 0) 
			         {
			             out.write(buf, 0, len);
			         }
			         
			         in.close();
			         out.close();
			     }
	 }
	 
	 public static String formatFileSize(long size) {
	        if (size < 1024) {
	            return String.format("%d B", size);
	        } else if (size < 1024 * 1024) {
	            return String.format("%.1f KB", size / 1024.0f);
	        } else if (size < 1024 * 1024 * 1024) {
	            return String.format("%.1f MB", size / 1024.0f / 1024.0f);
	        } else {
	            return String.format("%.1f GB", size / 1024.0f / 1024.0f / 1024.0f);
	        }
	    }
 
	 
	 
 }
//////////////////////////////////////////////////

