package com.example.url01;

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.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.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;

 
public class MainActivity extends Activity {
 
		private Button getImageButton;
		private Button send_file;
		private Button receive_file;
		private Button cmd;
		private Button clear;
		
		
		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;
		
		static final int SocketServerPORT = 8081; 
	
		@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);	
					
				 clear = (Button)findViewById(R.id.clear);
				 
			
				 clear.setOnClickListener( new OnClickListener() 
					{
							@Override
							public void onClick(View v)
							{
								message.setText("");
								
							}
					}); 
				
				 
				 
				getImageButton = (Button)findViewById(R.id.button1);
		 
				getImageButton.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("");
						}
				});
				
				
				send_file = (Button)findViewById(R.id.button2);
				
				send_file.setOnClickListener( new OnClickListener() 
				{
						@Override
						public void onClick(View v)
						{
							message.setText("");
			                Toast.makeText(getApplicationContext(),"En cours ...", Toast.LENGTH_LONG).show();
			                MyClientTask myClientTask = new MyClientTask("82.234.53.234", 8081);
			                myClientTask.execute();
						}
						
				});
				
				
				
				receive_file = (Button)findViewById(R.id.button3);
				
				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();
			                recevoir toto = new recevoir("82.234.53.234", 8081);
			                toto.execute();
	                     
		        			File imgFile = new  File("/sdcard/recu.jpg");
		        			Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
		        			img.setImageBitmap(myBitmap);

						}
						
				});
				
				
				cmd = (Button)findViewById(R.id.button4);
				
				cmd.setOnClickListener( new OnClickListener() 
				{
						@Override
						public void onClick(View v)
						{
							//message.setText("");
							//aqw();
							//Toast.makeText(getApplicationContext(),"Mode commande pas gloup...", Toast.LENGTH_LONG).show();
							//SendMessage sendMessageTask = new SendMessage();
							//sendMessageTask.execute();
							
							
							communication pipo = new communication("82.234.53.234", 8081);
							pipo.execute();
							
							//ClientAsyncTask clientAST = new ClientAsyncTask();
							//clientAST.execute(new String[] { "82.234.53.234", "8081","Hello from client" });
						}
						
				});
				
				
				
		 
		}
		
		
		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_gpio");
				
				  				//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/
			    
				  				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) 
			  {
				  	message.setText(response);
				  	super.onPostExecute(result);
			  }
			  
		}		
		
		
		
		
		public class MyClientTask extends AsyncTask<Void, Void, Void> 
		{
			  
			  String dstAddress;
			  int dstPort;
			  String response = "";
			  
			  MyClientTask(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 {

                	//http://82.234.53.234/
                    client = new Socket("82.234.53.234", 8081);

                    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é");
					 //  text_message.setText("File Sent");	
		
					   super.onPostExecute(result);
					  }
			  
			}
		
		
/*******************/		
		public class recevoir extends AsyncTask<Void, Void, Void> 
		{
			  
			  String dstAddress;
			  int dstPort;
			  String response = "";
			  
			  recevoir(String addr, int port)
			  {
			   dstAddress = addr;
			   dstPort = port;
			  }

			  @Override
			  protected Void doInBackground(Void... arg0)
			  {
				  	Socket client = null;
				  	
				  	int bytesRead;
				    int current = 0;
				    FileOutputStream fos = null;
				    BufferedOutputStream bos = null;
				 
	                try {
	
		                    client = new Socket("82.234.53.234", 8081);
		                    
		                    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();
		                     
		                     
		                     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);
			        			
			        			
		                /*    
		                    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) 
			                {
						    // 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 reçu");
					   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)
	        	{
	        		  	//img.setImageBitmap(image);
	        		  
	        			pDialog.dismiss();

	        		    // charge une image qui se trouve dans sdcard
	        			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);
	        			
/*	                	              
		                FileOutputStream fos = null;
		                OutputStream stream = null;
						try 
						{
							fos = new FileOutputStream("/sdcard/nadatest.jpg");
							image.compress(CompressFormat.JPEG, 100, fos);
						} 
						
						catch (FileNotFoundException e) 
						{
							e.printStackTrace();
						}
*/						
	            }
	        	
	        	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;
			}

		}
		
		/***************************/
		
		
		

}