package com.camera.simplemjpeg;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class capture_camera extends Activity 
{
	
			private Button btn_start_camera, btn_stop_camera;
			private ImageView capture;
			private TextView message;
			
			private Handler handler = new Handler();
			private Bitmap bitmap = null;
			
			
			@Override
			protected void onCreate(Bundle savedInstanceState) 
			{
				super.onCreate(savedInstanceState);
		
				setContentView(R.layout.capture_camera);
				
				message = (TextView)findViewById(R.id.message);	

				
				btn_start_camera = (Button)findViewById(R.id.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);
							Toast.makeText(getApplicationContext(),"Start polaroid...", Toast.LENGTH_LONG).show();
						    
						
						}
						
				});
				
				
				btn_stop_camera = (Button)findViewById(R.id.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);
						   Toast.makeText(getApplicationContext(),"Stop polaroid...", Toast.LENGTH_LONG).show();
						 
						}
						
				});
		
			}
			
			
			private Runnable timedTask = new Runnable()
	 		{

	 			@Override
	 			public void run() 
	 			{
	 				// TODO Auto-generated method stub
	 				
	 				capture = (ImageView)findViewById(R.id.image_camera);
	 				capture.setImageDrawable(null);
					communication pipo = new communication("82.234.53.234", 8080);
					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();
					  				
					 
					  		} 
					  		
					  		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);
	        			capture.setImageBitmap(bMapRotate);
	        			
					    
					  	super.onPostExecute(result);
				  }
				  
			}		
			
			


}
