package com.example.upload01;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
  
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;

import com.example.listviewcustom05.DbAdapter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

//http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106

//http://www.codicode.com/art/upload_files_from_android_to_a_w.aspx

//http://www.coderefer.com/android-upload-file-to-server/

//http://programmerguru.com/android-tutorial/how-to-upload-image-to-php-server/

public class MainActivity extends Activity 
{
     
    TextView messageText;
    Button uploadButton;
    Button downloadButton;
    Button listingButton;
    Button ecrire_CSV_Button;
    Button lire_CSV_Button;
    ProgressDialog pDialog;
    
    int serverResponseCode = 0;
    ProgressDialog dialog = null;
    String upLoadServerUri = null;
    
    String myJSON;
    String source_download = "";
    
  //  DbAdapter handler;
     
    /**********  File Path *************/
    
    final String uploadFilePath = Environment.getExternalStorageDirectory().toString()+ "/";
    final String uploadFileName = "mini_saved.jpg";
     
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        	super.onCreate(savedInstanceState);
        	setContentView(R.layout.activity_main);
        	
//        	handler = new DbAdapter(getApplicationContext());
//			handler.open();
          
        	
        	messageText  = (TextView)findViewById(R.id.messageText);
         
        	messageText.setText("Uploading file path " + uploadFileName+"'");
         
        	/************* Php script path ****************/
        	upLoadServerUri = "http://www.analog-design.net/WORKAREA/upload_server.php";
        	
        	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
     	   //get current date time with Date()
     	   Date date = new Date();
     	  // System.out.println(dateFormat.format(date));
        	
        	
     	    uploadButton = (Button)findViewById(R.id.uploadButton);
	        uploadButton.setOnClickListener(new OnClickListener() 
	        {            
	            		@Override
	            		public void onClick(View v) 
	            		{
	            			dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
	                 
	            			new Thread(new Runnable() 
	            			{
	            				public void run()
	            				{
	            					runOnUiThread(new Runnable() 
	            					{
	                                    public void run()
	                                    {
	                                        messageText.setText("uploading started.....");
	                                    }
	                                });                      
	                           
	            					uploadFile(uploadFilePath + "" + uploadFileName);
	            				}
	                      }).start();        
	            		}
	        });
	        
	        
	        downloadButton = (Button)findViewById(R.id.downloadButton);
	        downloadButton.setOnClickListener( new OnClickListener() 
			{
					@Override
					public void onClick(View v)
					{
					   if(source_download == "")
					   {
							Toast.makeText(MainActivity.this, "Selection empty !" , Toast.LENGTH_SHORT).show();
					   }
					   else
					   {	   
					        information info = new information();
					        String path = "http://analog-design.net/WORKAREA/" + source_download ;
					        
					        info.execute(path);

					        //info.execute("http://www.analog-design.net/ALARME/Videos/beach.jpeg");
						    Toast.makeText(MainActivity.this, source_download , Toast.LENGTH_SHORT).show();
					   }
					}
			});
	        
	        
	        
	        listingButton = (Button)findViewById(R.id.listingButton);
	        listingButton.setOnClickListener( new OnClickListener() 
			{
					@Override
					public void onClick(View v)
					{
						 //getData();
						 //Toast.makeText(MainActivity.this, "Query.", Toast.LENGTH_SHORT).show();
						//Intent image = new Intent(MainActivity.this, listing_backup.class);
			            //startActivity(image);
			            
			            Intent intent = new Intent(MainActivity.this, listing_backup.class);
			       	 	startActivityForResult(intent, 0);
				       
					}
			});
	        
	        ecrire_CSV_Button = (Button)findViewById(R.id.ecrire_CSV_Button);
	        ecrire_CSV_Button.setOnClickListener( new OnClickListener() 
			{
					@Override
					public void onClick(View v)
					{
						String chemin =  Environment.getExternalStorageDirectory().toString()+ "/csv.txt";
						CSV_write.writeCsvFile(chemin);
						  Toast.makeText(MainActivity.this, "CSV creation successful" , Toast.LENGTH_SHORT).show();
					}
			});
	        
	        lire_CSV_Button = (Button)findViewById(R.id.lire_CSV_Button);
	        lire_CSV_Button.setOnClickListener( new OnClickListener() 
			{
					@Override
					public void onClick(View v)
					{
						String chemin =  Environment.getExternalStorageDirectory().toString()+ "/csv.txt";
						CSV_read.readCsvFile(chemin);      
						Toast.makeText(MainActivity.this, "CSV creation successful" , Toast.LENGTH_SHORT).show();
					}
			});
	       
	      
    }
      
    public int uploadFile(String sourceFileUri) 
    {
           
          String fileName = sourceFileUri;
  
          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024; 
          File sourceFile = new File(sourceFileUri); 
           
          if (!sourceFile.isFile())
          {
               dialog.dismiss(); 
                
               Log.e("uploadFile", "Source File not exist :" + uploadFilePath + "" + uploadFileName);
                
               runOnUiThread(new Runnable() 
               {
                   public void run()
                   {
                       messageText.setText("Source File not exist :" + uploadFilePath + "" + uploadFileName);
                   }
               }); 
                
               return 0;
            
          }
          else
	      {
	               try 
	               { 
	                    
	                     // open a URL connection to the Servlet
	                   	FileInputStream fileInputStream = new FileInputStream(sourceFile);
	                   URL url = new URL(upLoadServerUri);
	                    
	                   // Open a HTTP  connection to  the URL
	                   conn = (HttpURLConnection) url.openConnection(); 
	                   conn.setDoInput(true); // Allow Inputs
	                   conn.setDoOutput(true); // Allow Outputs
	                   conn.setUseCaches(false); // Don't use a Cached Copy
	                   conn.setRequestMethod("POST");
	                   conn.setRequestProperty("Connection", "Keep-Alive");
	                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
	                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
	                   conn.setRequestProperty("uploaded_file", fileName); 
	                    
	                   dos = new DataOutputStream(conn.getOutputStream());
	          
	                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
	            //       dos.writeBytes("Content-Disposition: form-data; name="uploaded_file";filename="" + fileName + """ + lineEnd);
	                                             
	                   dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName +"\"" + lineEnd);
                                             
	                   dos.writeBytes(lineEnd);
          
	                   // create a buffer of  maximum size
	                   bytesAvailable = fileInputStream.available(); 
	          
	                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
	                   buffer = new byte[bufferSize];
	          
	                   // read file and write it into form...
	                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
	                      
	                   while (bytesRead > 0)
	                   {
	                        
		                     dos.write(buffer, 0, bufferSize);
		                     bytesAvailable = fileInputStream.available();
		                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
		                     bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
	                      
	                    }
          
	                   // send multipart form data necesssary after file data...
	                   dos.writeBytes(lineEnd);
	                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	          
	                   // Responses from the server (code and message)
	                   serverResponseCode = conn.getResponseCode();
	                   String serverResponseMessage = conn.getResponseMessage();
	                     
	                   Log.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);
                    
	                   if(serverResponseCode == 200)
	                   {
                        
	                       runOnUiThread(new Runnable() 
	                       {
	                            public void run()
	                            {
	                                //String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
	                                //              +" http://www.androidexample.com/media/uploads/"
	                                //              +uploadFileName;
	                                String msg = "File Upload Completed.\n\n"; 
	                                messageText.setText(msg);
	                                Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
	                            }
	                        });                
	                   }    
                    
	                   //close the streams //
	                   fileInputStream.close();
	                   dos.flush();
	                   dos.close();
                     
              } // try
               
               
              catch (MalformedURLException ex)
              {
                   
                  dialog.dismiss();  
                  ex.printStackTrace();
                   
                  runOnUiThread(new Runnable()
                  {
                      public void run() 
                      {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                      }
                  });
                   
                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
              } 
               
              catch (Exception e) 
              {
                   
                  dialog.dismiss();  
                  e.printStackTrace();
                   
                  runOnUiThread(new Runnable() 
                  {
                      public void run() 
                      {
                          messageText.setText("Got Exception : see logcat ");
                          Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
              }
               
              dialog.dismiss();       
              return serverResponseCode; 
               
           } // End else block 
         } 
    
    
    /************************/
	public class information extends AsyncTask<String, String, String>
    {
		
		protected void onPreExecute() 
		{
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading file from server ....");
            pDialog.show();
 
        }
		
        @Override
        protected String doInBackground(String... params) 
        {
        	
            try
            {
            	URL url = new URL(params[0]);
                //URL url = new URL("http://www.analog-design.net/ALARME/Videos/beach.jpeg");
                InputStream is = new BufferedInputStream(url.openStream(), 8192);
               
            } 
            
            catch(Exception e)
            {}
            
	            
           // ecriture dans sdcard
            InputStream input;
            String msg = "";
            
//            String FilePath = Environment.getExternalStorageDirectory().toString()+ "/titi.txt";                   //   "/receive.jpg";
//            File file_receive = new File(FilePath);

           /* if (file_receive.exists())
            {
            	file_receive.delete();
         	   //Toast.makeText(MainActivity.this, "Existe ...", Toast.LENGTH_SHORT).show();
            }*/ 
            
            try
            {
	                //URL url = new URL ("http://www.analog-design.net/ALARME/Videos/beach.jpeg");
            		URL url = new URL(params[0]);
            		
            		String path=url.toString();
                    File f=new File(path);
            		String filename = f.getName();
            		
            		
            		String FilePath = Environment.getExternalStorageDirectory().toString()+ "/" + filename;                   //   "/receive.jpg";
                    File file_receive = new File(FilePath);
            		
	                input = url.openStream();
	                byte[] buffer = new byte[1500];
	                OutputStream output = new FileOutputStream (FilePath);    // verifier s'il existe  ???
	                try
	                {    
		                    int bytesRead = 0;
		                    while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
		                    {
		                        output.write(buffer, 0, bytesRead);
		                    }
		                	msg = "succes";
	
	                }
	                finally
	                {
	                    output.close();
	                    buffer=null;
	                }
            }
            catch(Exception e)
            {
            	msg = "error";
                Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
            }
	            
            return(msg);
           
        }

        @Override
        protected void onPostExecute(String msg) 
        {
        	
        	if(msg.equals("succes"))
        	{
        			pDialog.dismiss();
        			//Toast.makeText(MainActivity.this, "Bravo ", Toast.LENGTH_SHORT).show();
            }
        	
        	else
        	{
                  pDialog.dismiss();
                  Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
            }
        	
          
        }
    }	
	
    /**********************/
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		  
		  if(data != null && data.hasExtra("valeur_retour"))
		  {
			  		source_download  = data.getExtras().getString("valeur_retour");
				  
				   // maintenant on va telecharger le ficiher choisi et faire la restauration csv ....
				   
				/*  try
	              {
	              		File myFile = new File("/mnt/sdcard/" + fichier);
	           			FileInputStream fIn = new FileInputStream(myFile);
	           			BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
	           			String aDataRow = "";
	          			String aBuffer = "";
	
	          			while ((aDataRow = myReader.readLine()) != null)
	              		{
	              			aBuffer += aDataRow + "\n";
	              		}
	              		text.setText(aBuffer);
	              		myReader.close();
	      		} 
	              
	            catch (Exception e) 
	            {
	      			Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
	      		}
				  
				ActionBar ab = getActionBar();
				String titre = "Utils01:  " + fichier; 
				ab.setTitle(titre);*/
		  }
	} 
	
}