package com.camera.simplemjpeg;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
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.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 flux_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;
			
			String status = "";

			
			@Override
			protected void onCreate(Bundle savedInstanceState) 
			{
				super.onCreate(savedInstanceState);
		
				setContentView(R.layout.flux_camera);
				
				message = (TextView)findViewById(R.id.message);	
				
				try {
						File handle = new File("/sdcard/config_flux_camera.txt");
						// verifier si un fichier existe
						if( handle.exists() ) 
						{
							// existe, donc on lit le status
			                BufferedReader br = null;
			                StringBuffer chaine = new StringBuffer();
			                String line = "";
			                br = new BufferedReader(new FileReader("/sdcard/config_flux_camera.txt"));
			    			while ((line = br.readLine()) != null) 
			    			{
			    				status += line; // + "\n";
			    			}
			    			message.setText("Etat ouverture activity : " + status);	
						}
						else
						{   // config par defaut
							handle.createNewFile();	
							FileWriter fw = new FileWriter(handle.getAbsoluteFile());
			                BufferedWriter bw = new BufferedWriter(fw);
			                bw.write("");
			                bw.close();
						}
				}
				catch (IOException e)
				{
	                e.printStackTrace();
	            }
				
				
				btn_start_camera = (Button)findViewById(R.id.start_flux);
				btn_stop_camera = (Button)findViewById(R.id.stop_flux);
				
				
				
				/***********************************/		
				
//				if(status.equals("stop"))
//				{
					btn_start_camera.setEnabled(true);
					btn_start_camera.setOnClickListener( new OnClickListener() 
					{
							@Override
							public void onClick(View v)
							{
								btn_start_camera.setEnabled(false);
								btn_stop_camera.setEnabled(true);
								Toast.makeText(getApplicationContext(),"Start flux", Toast.LENGTH_LONG).show();
					            communication_start pipo = new communication_start("82.234.53.234", 8080);
								pipo.execute();
								
								// on ecrit 
								try {
										status = "start";
										File handle = new File("/sdcard/config_flux_camera.txt");
										// on vide la contenu du fichier
										PrintWriter writer = new PrintWriter(handle);
										writer.print("");
										writer.close();
										// ecriture
										FileWriter fw = new FileWriter(handle.getAbsoluteFile());
										BufferedWriter bw = new BufferedWriter(fw);
										bw.write(status);
										bw.close();	
								}
								catch (IOException e)
								{
					                e.printStackTrace();
					            }
				                
								message.setText(status);
					            
							}
							
					});
					
//				}
				
				
//				if(status.equals("start"))
//				{
					btn_stop_camera.setEnabled(false);
					btn_stop_camera.setOnClickListener( new OnClickListener() 
					{
							@Override
							public void onClick(View v)
							{
							   btn_start_camera.setEnabled(true);
							   btn_stop_camera.setEnabled(false);
							   Toast.makeText(getApplicationContext(),"Stop flux", Toast.LENGTH_LONG).show();
							   communication_stop stop = new communication_stop("82.234.53.234", 8080);
							   stop.execute();
							   
							   // on ecrit
								try {
										status = "stop";
										File handle = new File("/sdcard/config_flux_camera.txt");
										// on vide la contenu du fichier
										PrintWriter writer = new PrintWriter(handle);
										writer.print("");
										writer.close();
									    // ecriture
										FileWriter fw = new FileWriter(handle.getAbsoluteFile());
										BufferedWriter bw = new BufferedWriter(fw);
										bw.write(status);
										bw.close();	
	
								}
								catch (IOException e)
								{
					                e.printStackTrace();
					            }
								
								message.setText(status);
							}
							
					});
				}	
				
		
//			}
			

			protected void onStop()
			{
			   super.onStop();
			   Toast.makeText(getApplicationContext(),"Tuer le processus", Toast.LENGTH_LONG).show();	
			   
			  
			}
			
			protected void onResume()
			{
			   super.onResume();
			   Toast.makeText(getApplicationContext(),"Le retour", Toast.LENGTH_LONG).show();	
			   
			  
			}
			
			
	 		
			public class communication_start extends AsyncTask<Void, Void, Void> 
			{
				  
				  String dstAddress;
				  int dstPort;
				  String response = "";
				  
				  communication_start(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_flux_start");
					
					  			/*
					  				
					  			  	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);
				  }
				  
			}		
			
			
			public class communication_stop extends AsyncTask<Void, Void, Void> 
			{
				  
				  String dstAddress;
				  int dstPort;
				  String response = "";
				  
				  communication_stop(String addr, int port)
				  {
					  dstAddress = addr;
					  dstPort = port;
				  }

				  @Override
				  protected Void doInBackground(Void... arg0)
				  {
				   
					  		Socket patoche = null;
				   
					  		try {
					  				patoche = new Socket(dstAddress, dstPort);
				    
					  				// envoi un message au serveur
					  				BufferedReader br = new BufferedReader(new InputStreamReader(patoche.getInputStream()));
					  				PrintWriter pw = new PrintWriter(patoche.getOutputStream(), true);
					  				pw.println("cmd_flux_stop");
					
					  			
				                     if (patoche != null) patoche.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(patoche != null)
					  			{
					  				try {
					  						patoche.close();
					  				} 
					  				
					  				catch (IOException e) 
					  				{
					  					// TODO Auto-generated catch block
					  					e.printStackTrace();
					  				}
					  			}
					  		}
					  		
					  		return null;
				  }

				  @Override
				  protected void onPostExecute(Void result) 
				  {
					  	super.onPostExecute(result);
				  }
				  
			}		


}
