package com.example.url04;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import java.io.*;

 
public class MainActivity extends Activity {
 
		private Button button_url;
		private Button button_send_file;
		private Button button_receive_file;
		private Button btn_start_camera, btn_stop_camera;
		private Button button_clear;
		
		private Handler handler = new Handler();
		
		TextView textResponse;
		
		private Socket client;
	    private FileInputStream fileInputStream;
	    private BufferedInputStream bufferedInputStream;
	    private OutputStream outputStream;
	    private Button button;
	    TextView message;
		
		
		private ProgressDialog progressDialog;
		private Bitmap bitmap = null;
		private String text = null;
 
		ProgressDialog pDialog;
	    Bitmap b;
	    ImageView img;
		
	    EditText editTextAddress;
		Button buttonConnect;
		
	    /////////////////////////////////
		@Override
		public void onCreate(Bundle savedInstanceState)
		{
				super.onCreate(savedInstanceState);
				setContentView(R.layout.activity_main);
				
				 textResponse = (TextView)findViewById(R.id.response);	
				 message = (TextView)findViewById(R.id.message);	
					
				 button_clear = (Button)findViewById(R.id.clear);
				 button_clear.setOnClickListener( new OnClickListener() 
					{
							@Override
							public void onClick(View v)
							{
								message.setText("");
								
							}
					}); 
				
				 
				 
				button_url = (Button)findViewById(R.id.button1);
				button_url.setOnClickListener( new OnClickListener() 
				{
						@Override
						public void onClick(View v)
						{
							message.setText("");
							img = (ImageView)findViewById(R.id.imageView1);
							img.setImageDrawable(null);
					        information info = new information();
					        info.execute("");
						}
				});
				
				
				button_send_file = (Button)findViewById(R.id.button2);
				button_send_file.setOnClickListener( new OnClickListener() 
				{
						@Override
						public void onClick(View v)
						{
							message.setText("");
			                Toast.makeText(getApplicationContext(),"En cours ...", Toast.LENGTH_LONG).show();
			                envoi_fichier_task instance_reception_fichier = new envoi_fichier_task("82.234.53.234", 8081);
			                instance_reception_fichier.execute();
						}
						
				});
				
				
				img = (ImageView)findViewById(R.id.imageView1);
				
				button_receive_file = (Button)findViewById(R.id.button3);
				button_receive_file.setOnClickListener( new OnClickListener() 
				{
						@Override
						public void onClick(View v)
						{
							message.setText("");
							img = (ImageView)findViewById(R.id.imageView1);
							img.setImageDrawable(null);
							Toast.makeText(getApplicationContext(),"Mode réception ...", Toast.LENGTH_LONG).show();
			                recoi_fichier_task instance_recoi_fichier = new recoi_fichier_task("82.234.53.234", 8081);
			                instance_recoi_fichier.execute();
	                     
		        		//	File imgFile = new  File("/sdcard/recu.jpg");
		        		//	Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
		        		//	img.setImageBitmap(myBitmap);

						}
						
				});
				
				
			
				
				btn_start_camera = (Button)findViewById(R.id.btn_start_camera);
				btn_start_camera.setEnabled(true);
				btn_start_camera.setOnClickListener( new OnClickListener() 
				{
						@Override
						public void onClick(View v)
						{
							handler.post(timedTask);
							btn_start_camera.setEnabled(false);
							btn_stop_camera.setEnabled(true);
						    
							//img = (ImageView)findViewById(R.id.imageView1);
							//img.setImageDrawable(null);
							//communication pipo = new communication("82.234.53.234", 8081);
							//pipo.execute();
						}
						
				});
				
				btn_stop_camera = (Button)findViewById(R.id.btn_stop_camera);
				btn_stop_camera.setEnabled(false);
				btn_stop_camera.setOnClickListener( new OnClickListener() 
				{
						@Override
						public void onClick(View v)
						{
							handler.removeCallbacks(timedTask);
							btn_start_camera.setEnabled(true);
							btn_stop_camera.setEnabled(false);
						   // cnt = 0;
						   // counter.setText(String.valueOf(cnt));
						}
						
				});
		 
		}
		
	    /////////////////////////////////
		
		
		private Runnable timedTask = new Runnable()
 		{

 			@Override
 			public void run() 
 			{
 				// TODO Auto-generated method stub
 				
 				img = (ImageView)findViewById(R.id.imageView1);
				img.setImageDrawable(null);
				communication pipo = new communication("82.234.53.234", 8081);
				pipo.execute();
 				
 				handler.postDelayed(timedTask, 5000);
 			}
 		};
		

		public class communication extends AsyncTask<Void, Void, Void> 
		{
			  
			  String dstAddress;
			  int dstPort;
			  String response = "";
			  
			  communication(String addr, int port)
			  {
				  dstAddress = addr;
				  dstPort = port;
			  }

			  @Override
			  protected Void doInBackground(Void... arg0)
			  {
			   
				  		Socket socket = null;
			   
				  		try {
				  				socket = new Socket(dstAddress, dstPort);
			    
				  				// envoi un message au serveur
				  				BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				  				PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
				  				pw.println("cmd_camera");
				
				  				//http://android-er.blogspot.fr/2014/02/android-sercerclient-example-client.html
				  				//http://codeoncloud.blogspot.fr/2014/06/android-tcpip-client-server-socket_15.html
				  				//http://androidsrc.net/android-client-server-using-sockets-client-implementation/
				  				
				  			  	int bytesRead;
							    int current = 0;
							    FileOutputStream fos = null;
							    BufferedOutputStream bos = null;
				  				
				  				
				  				int FILE_SIZE = 6022386;
			                    String  FILE_TO_RECEIVED = "/sdcard/capture_PI.jpg";
			                    
			                    byte [] mybytearray  = new byte [FILE_SIZE];
			                    InputStream is = socket.getInputStream();
			                    fos = new FileOutputStream(FILE_TO_RECEIVED);
			                    bos = new BufferedOutputStream(fos);
			                    bytesRead = is.read(mybytearray,0,mybytearray.length);
			                    current = bytesRead;
			                    
			                    
			                    do {
			                        bytesRead =
			                           is.read(mybytearray, current, (mybytearray.length-current));
			                        if(bytesRead >= 0) current += bytesRead;
			                     } while(bytesRead > -1);

			                     bos.write(mybytearray, 0 , current);
			                     bos.flush();
			                     
			                     
			                     if (fos != null) fos.close();
			                     if (bos != null) bos.close();
			                     if (socket != null) socket.close();
				  				
				  		//		response = "coucou";
				  				
			    /*
				  				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
				  				byte[] buffer = new byte[1024];
			    
				  				int bytesRead;
				  				InputStream inputStream = socket.getInputStream();
			    
			  
				  				while ((bytesRead = inputStream.read(buffer)) != -1)
				  				{
				  					byteArrayOutputStream.write(buffer, 0, bytesRead);
				  					response += byteArrayOutputStream.toString("UTF-8");
				  				}
				 */ 				

				  		} 
				  		
				  		catch (UnknownHostException e)
				  		{
				  			// TODO Auto-generated catch block
				  			e.printStackTrace();
				  			response = "UnknownHostException: " + e.toString();
				  		} 
				  		
				  		catch (IOException e)
				  		{
				  			// TODO Auto-generated catch block
				  			e.printStackTrace();
				  			response = "IOException: " + e.toString();
				  		}
				  		
				  		finally
				  		{
				  			
				  			if(socket != null)
				  			{
				  				try {
				  						socket.close();
				  				} 
				  				
				  				catch (IOException e) 
				  				{
				  					// TODO Auto-generated catch block
				  					e.printStackTrace();
				  				}
				  			}
				  		}
				  		
				  		return null;
			  }

			  @Override
			  protected void onPostExecute(Void result) 
			  {
				  	String s = "fin de communication";
				    message.setText(s); // response
				    
				    
				 // charge une image qui se trouve dans sdcard
        			String imageInSD = "/sdcard/capture_PI.jpg";
        			BitmapFactory.Options bOptions = new BitmapFactory.Options();
        			bOptions.inTempStorage = new byte[16*1024];
        	               
        			bitmap = BitmapFactory.decodeFile(imageInSD,bOptions);
        			
        			// rotation
        			Matrix mat = new Matrix();
       		        mat.postRotate(-90);
        		    Bitmap bMapRotate = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);
        			img.setImageBitmap(bMapRotate);
        			
				    
				  	super.onPostExecute(result);
			  }
			  
		}		
		
		
		
		
		public class envoi_fichier_task extends AsyncTask<Void, Void, Void> 
		{
			  
			  String dstAddress;
			  int dstPort;
			  String response = "";
			  
			  envoi_fichier_task(String addr, int port)
			  {
				  dstAddress = addr;
				  dstPort = port;
			  }

			  @Override
			  protected Void doInBackground(Void... arg0) 
			  {
			   
				  Socket client = null;
			   
			      File file = new File("sdcard/tmp.jpg"); //create file instance

                try {

                	
                    client = new Socket(dstAddress, dstPort);
                    
                    // envoi un message au serveur
	  				BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
	  				PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
	  				pw.println("cmd_android_send");

                    byte[] mybytearray = new byte[(int) file.length()]; //create a byte array to file

                    fileInputStream = new FileInputStream(file);
                    bufferedInputStream = new BufferedInputStream(fileInputStream);

                    bufferedInputStream.read(mybytearray, 0, mybytearray.length); //read the file

                    outputStream = client.getOutputStream();

                    outputStream.write(mybytearray, 0, mybytearray.length); //write file to the output stream byte by byte
                    outputStream.flush();
                    
                    
                    
                    // reponse
//                    BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
//                    String mstr = br.readLine();
//                    Toast.makeText(getApplicationContext(),mstr, Toast.LENGTH_LONG).show();
                    
                    
                    bufferedInputStream.close();
                    outputStream.close();
                    client.close();
			    



			   } 
			   
			   catch (UnknownHostException e) 
                {
			    // TODO Auto-generated catch block
			    e.printStackTrace();
			    response = "UnknownHostException: " + e.toString();
			   } catch (IOException e) {
			    // TODO Auto-generated catch block
			    e.printStackTrace();
			    response = "IOException: " + e.toString();
			   }finally{
			    if(client != null){
			     try {
			      client.close();
			     } catch (IOException e) {
			      // TODO Auto-generated catch block
			      e.printStackTrace();
			     }
			    }
			   }
			   return null;
			  }

					  @Override
					  protected void onPostExecute(Void result)
					  {
					   textResponse.setText(response);
					   message.setText("Fichier envoyé");
					   super.onPostExecute(result);
					  }
			  
			}
		
		
/*******************/		
		public class recoi_fichier_task extends AsyncTask<Void, Void, Bitmap> 
		{
			  
			  String dstAddress;
			  int dstPort;
			  String response = "";
			  
			  recoi_fichier_task(String addr, int port)
			  {
				  dstAddress = addr;
				  dstPort = port;
			  }

			  @Override
			  protected Bitmap doInBackground(Void... arg0)
			  {
				  	Socket client = null;
				  	
				  	int bytesRead;
				    int current = 0;
				    FileOutputStream fos = null;
				    BufferedOutputStream bos = null;
				 
	                try {
	
		                    client = new Socket(dstAddress, dstPort);
		                    
		                    // envoi la commande au serveur
			  				BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
			  				PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
			  				pw.println("cmd_android_receive");
		                    
			  				// revoi un fichier et stockage dans sdcard
		                    int FILE_SIZE = 6022386;
		                    String  FILE_TO_RECEIVED = "/sdcard/recu.jpg";
		                    
		                    byte [] mybytearray  = new byte [FILE_SIZE];
		                    InputStream is = client.getInputStream();
		                    fos = new FileOutputStream(FILE_TO_RECEIVED);
		                    bos = new BufferedOutputStream(fos);
		                    bytesRead = is.read(mybytearray,0,mybytearray.length);
		                    current = bytesRead;
		                    
		                    do {
		                        	bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
		                        	if(bytesRead >= 0) current += bytesRead;
		                     } while(bytesRead > -1);

		                     bos.write(mybytearray, 0 , current);
		                     bos.flush();
		                     
		                    // img = (ImageView)findViewById(R.id.imageView1);
		                    // Bitmap bitMap = BitmapFactory.decodeStream(is);
			                // 	img.setImageBitmap(bitmap);
		
/*		                     
		                     byte[] buffer = new byte[30000];
		                     int current = 0;
		                     int bytesRead=0;
		                     
		                     InputStream is = app.sck.getInputStream();
		                     FileOutputStream fos = new FileOutputStream(file);
		                     BufferedOutputStream bos = new BufferedOutputStream(fos);
		                     bytesRead = is.read(buffer,0,buffer.length);
		                     current = bytesRead;

		                     do {
		                         bytesRead = is.read(buffer, current, (buffer.length-current));
		                         if(bytesRead >= 0) current += bytesRead;
		                                } while(bytesRead > -1);
*/
		                     ByteArrayInputStream inputStream = new ByteArrayInputStream(mybytearray);
		                     Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                           //               img.setImageBitmap(bitmap);	
		                     int width = bitmap.getWidth();
		                     String s = Integer.toString(width);
		                     Log.d("Client", s);

		                //     BitmapFactory.decodeFile(String pathName)
		                //     BitmapFactory.decodeStream(Inputstream)
		                //     BitmapFactory.decodeResource(Resource res, int id)  
		                //     BitmapFactory.decodeByteArray(byte[] data)

		                    
		                   //  img.setImageBitmap(bMap);	
		                     
		                     
		                     if (fos != null) fos.close();
		                     if (bos != null) bos.close();
		                     if (client != null) client.close();
		                     
		                     
		                 	
		                 	
		                 	
		                 	
		                 	
		                    // String imageInSD = "/sdcard/recu.jpg";
			        		//	BitmapFactory.Options bOptions = new BitmapFactory.Options();
			        		//	bOptions.inTempStorage = new byte[16*1024];
			        	               
			        		//	bitmap = BitmapFactory.decodeFile(imageInSD,bOptions);
			        		//	img.setImageBitmap(bitmap);
			        			
			        			/*************************************************/
/*		                 	
		                 	int day, month, year;
		                    int second, minute, hour;
		                    GregorianCalendar date = new GregorianCalendar();

		                    day = date.get(Calendar.DAY_OF_MONTH);
		                    month = date.get(Calendar.MONTH);
		                    year = date.get(Calendar.YEAR);

		                    second = date.get(Calendar.SECOND);
		                    minute = date.get(Calendar.MINUTE);
		                    hour = date.get(Calendar.HOUR);

		                    String name=(hour+""+minute+""+second+""+day+""+(month+1)+""+year);
		                    String tag=name+".jpg";
		                    String fileName = sourceFileUri.replace(sourceFileUri,tag);
*/		                 	
		                 	/***************************************************/
		                 	
		                 	
		                /*    
		                    File file = new File( "/sdcard/recu.jpg");

		                    
		                    ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
		                    byte[] bytes = null;
		                    FileOutputStream fos = null;
		                   
		                     try {
								bytes = (byte[])ois.readObject();
							} catch (ClassNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
		                     fos = new FileOutputStream(file);
		                     fos.write(bytes);
		                */   
		                    
		                  /*  
		                    File myFile = new File ("/sdcard/reception.jpg");
		                    FileInputStream fis = new FileInputStream(myFile);
		                    OutputStream os = client.getOutputStream();
		                    int filesize = (int) myFile.length();

		                    byte [] buffer  = new byte [filesize];
	                        int bytesRead =0;
		                    
	                        while ((bytesRead = fis.read(buffer)) > 0) 
		                    {
		                         os.write(buffer, 0, bytesRead);
		                    }
		                    
	                        os.flush();
		                    os.close();
		                    fis.close();
		                    Log.d("Client", "Client sent message");
		                    
		                    client.close();*/
	
				   } 
			   
					catch (UnknownHostException e) 
			        {
					    e.printStackTrace();
					    response = "UnknownHostException: " + e.toString();
			        } 
	                
	                catch (IOException e)
	                {
					    e.printStackTrace();
					    response = "IOException: " + e.toString();
	                }
	                
	                finally
	                {
					    if(client != null)
					    {
						     try {
						    	 client.close();
						     } 
						     
						     catch (IOException e)
						     {
						    	 e.printStackTrace();
						     }
					    }
					 }
					 
	                //return null;
	                return bitmap;
			  }

			  @Override
			  protected void onPostExecute(Bitmap image)
			  {
				 // img.setImageBitmap(image);
				  
				  //http://techlovejump.com/android-load-image-url-internet/

						File imgFile = new  File("/sdcard/recu.jpg");
	        			Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
	        			img.setImageBitmap(myBitmap);
				  
				  // textResponse.setText(response);
				   message.setText("Fichier reçu - bingo");
				  // super.onPostExecute(result);
			  }
			  
		}
		

/*******************/		

		
		public class information extends AsyncTask<String, String, Bitmap>
	    {
			
			protected void onPreExecute() 
			{
	            super.onPreExecute();
	            pDialog = new ProgressDialog(MainActivity.this);
	            pDialog.setMessage("Loading Image ....");
	            pDialog.show();
	 
	        }
			
	        @Override
	        protected Bitmap doInBackground(String... arg0) 
	        {
	        	
	            try
	            {
	                URL url = new URL("http://www.analog-design.net/ALARME/Videos/beach.jpeg");
	                InputStream is = new BufferedInputStream(url.openStream(), 8192);
	                bitmap = BitmapFactory.decodeStream(is);
	            } 
	            
	            catch(Exception e)
	            {}
	            
/*	            
	            // ecriture dans sdcard
	            InputStream input;
	            try
	            {
	                URL url = new URL ("http://www.analog-design.net/ALARME/Videos/beach.jpeg");
	                input = url.openStream();
	                byte[] buffer = new byte[1500];
	                OutputStream output = new FileOutputStream ("/sdcard/url.jpg");
	                try
	                {    
		                    int bytesRead = 0;
		                    while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
		                    {
		                        output.write(buffer, 0, bytesRead);
		                    }
	                }
	                finally
	                {
	                    output.close();
	                    buffer=null;
	                }
	            }
	            catch(Exception e)
	            {
	                Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
	            }
*/	            
	            return bitmap;
	           
	        }

	        @Override
	        protected void onPostExecute(Bitmap image) 
	        {
	        	
	        	if(image != null)
	        	{
	        		  	
	        			pDialog.dismiss();
	/*        		  
	        			String imageInSD = "/sdcard/url.jpg";
	        			BitmapFactory.Options bOptions = new BitmapFactory.Options();
	        			bOptions.inTempStorage = new byte[16*1024];
	        	               
	        			bitmap = BitmapFactory.decodeFile(imageInSD,bOptions);
	        			img.setImageBitmap(bitmap);
	*/        			
	        			
	        		/* on affiche : pas de chargement a partir de la SDcard */
	        			img.setImageBitmap(bitmap);
		
	            }
	        	
	        	else
	        	{
	                  pDialog.dismiss();
	                  Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
	            }
	        	
	          
	        }
	    }
		
		
		
		/*************************/
		
		private class SendMessage extends AsyncTask<Void, Void, Void> 
		{

			private Socket client;
			private PrintWriter printwriter;
			
			PrintWriter out;
		    BufferedReader in;
			
			@Override
			protected Void doInBackground(Void... params) 
			{
				try {

					client = new Socket("82.234.53.234", 8081); // connect to the server
					
					
					//send the message to the server
	               // out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
					
					printwriter = new PrintWriter(client.getOutputStream(), true);
					printwriter.write("messsage pour le test ..."); // write the message to output stream
					printwriter.flush();
					
					BufferedReader in = null;
					
					  in = new BufferedReader(new InputStreamReader(client.getInputStream()));
					  System.out.println(in.readLine()); // read from server

					
				//	InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
				//	BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // get the client message
				//	String message_recu = bufferedReader.readLine();
				//	message.setText("toto");
					
				//	BufferedReader br =new BufferedReader(new InputStreamReader(client.getInputStream()));
	            //    String mstr=br.readLine();
				//	message.setText(mstr);
					
					
					printwriter.close();
					client.close(); // closing the connection

				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}

		}
		
		/***************************/
		
		
		@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.
			int id = item.getItemId();
			if (id == R.id.action_settings) {
				return true;
			}
			return super.onOptionsItemSelected(item);
		}


}