package com.camera.simplemjpeg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;



import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

//import android.os.AsyncTask;


import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Switch;


import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;


import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;

import java.io.InputStream;
import java.net.URL;
import java.io.*;
import java.net.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.ActionBar;
import android.util.Log;

import java.net.InetAddress;

public class xxxxxxxsysteme extends Activity{
	
	private boolean position = false;
	private String message = "";
	
	Button alarm;
	Button button_capture_camera;
	TextView champ_connexion;
	TextView champ_reception;
	ImageView capture_image;
	TextView textResponse;

	 Bitmap bitmap;
    ProgressDialog pDialog;
    String nom_image = "";

 
	public void onCreate(Bundle savedInstanceState) 
	{
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.systeme);
		
		ActionBar actionBar = getActionBar();
		actionBar.show();
				
		alarm = (Button) findViewById(R.id.button_commande);
		
		// chargement de la configuration
		alarm.setText("Chargement...");
		
		champ_connexion = (TextView) findViewById(R.id.champ_connexion);
		champ_reception = (TextView) findViewById(R.id.champ_reception);
		button_capture_camera = (Button) findViewById(R.id.button_capture_camera);
		capture_image = (ImageView)findViewById(R.id.img);
		textResponse = (TextView)findViewById(R.id.response);
       
   	 	if(isConnected())
   	 	{
   	 		champ_connexion.setBackgroundColor(0xFF00CC00);
   	 		champ_connexion.setText("Connexion réseau");
   	 		//new HttpAsyncTask().execute("http://analog-design.net/WORKAREA/lire_etat_alarme.php");
   	 		new HttpAsyncTask().execute("http://damien.bruvier.free.fr/Rpi/lire_etat_alarme.php");
   	 	}
   	 	else
   	 	{
   	 		champ_connexion.setText("Probléme avec le réseau");
   	 		// on cache le bouton
   	 		alarm.setVisibility(View.GONE);
   	 		champ_connexion.setBackgroundColor(Color.RED);
   	 		//alarm.setVisibility(View.VISIBLE);

   	 	}      
		
   	 	//liaison_raspberry();
   	 	//test();
		
		alarm.setOnClickListener(new OnClickListener() 
 	 	{
   	 
   	 		  @Override
   	 		  public void onClick(View arg0) {
   	 			  if(!position)
   	 			  {	  
   	 				  alarm.setText("ALARME ON");
   	 				  position = true;
   	 				  message = "Alarme active"; 
   	 				  new MyAsyncTask().execute("on");	
   	 			  }	  
   	 			  else
   	 			  {	  
   	 				  alarm.setText("ALARME OFF");
   	 				  position = false;
   	 				  message = "Alarme désactivée"; 
   	 				  new MyAsyncTask().execute("off");	
   	 
   	 			  }	 	  
   	 			  
   	 		     Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
   	 
   	 		  }
   	 	});
		
		
		button_capture_camera.setOnClickListener(new View.OnClickListener()
		{
	      	public void onClick(View v) 
	      	{
	      		capture_cameraClick();
	      	}
	     });
		
		
		//new HttpAsyncTask().execute("http://analog-design.net/WORKAREA/lire_etat_alarme.php");
		//String adresse =  "http://damien.bruvier.free.fr/Rpi/mise_a_jour_alarme.php";
		//new HttpAsyncTask().execute(adresse);
		
	}
	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu)
	{
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.items, menu);
    	return super.onCreateOptionsMenu(menu);
    }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	
	    	super.onOptionsItemSelected(item);
	    	
	    	switch(item.getItemId()){
		    	
		    	
		    	case R.id.GPIO:
		    		Toast.makeText(getBaseContext(), "Selection GPIO", Toast.LENGTH_SHORT).show();
		    		// Intent gpioIntent = new Intent(this,gpio.class);
		            // startActivity(gpioIntent);
		    		break;
		    		
		    	case R.id.musique:
		    		Toast.makeText(getBaseContext(), "Selection du player", Toast.LENGTH_SHORT).show();
		    		//Intent playerIntent = new Intent(this,mediaplayer.class);
		            //startActivity(playerIntent);
		    		break;
		    		
		    		
		    		
		    	case R.id.camera:
		    		Toast.makeText(getBaseContext(), "Selection Camera", Toast.LENGTH_SHORT).show();
		    		// Intent productIntent = new Intent(this,camera.class);
		            // startActivity(productIntent);
		         // return true;
		    		break;
		    		
		    	//case R.id.fichier:
		    	//	Toast.makeText(getBaseContext(), "Selection du browser", Toast.LENGTH_SHORT).show();
		    		//Intent browserIntent = new Intent(this,listing_fichiers.class);
		            //startActivity(browserIntent);
		    	//	break;	
		    		
		    	//case R.id.video:
		    	//	Toast.makeText(getBaseContext(), "You selected Video", Toast.LENGTH_SHORT).show();
		    	//	break;
		    		
		    	//case R.id.email:
		    	//	Toast.makeText(getBaseContext(), "You selected EMail", Toast.LENGTH_SHORT).show();
		    	//	break;
		    		
	    	}
	    	
	    	return true;
    	
    }
	
	
	 public boolean isConnected()
		{
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			if (networkInfo != null && networkInfo.isConnected()) 
				return true;
			else
				return false;
		}
	 
	 public void liaison_raspberry()
	 {
		 	
		 	InetAddress in;
		 	in = null;
		 	String reponse = "";
	 
		 	try {
		 			
		 			in = InetAddress.getByName("www.google.fr");
		 	} 
	 
		 	catch (UnknownHostException e) 
		 	{
		 		e.printStackTrace();
		 	}
	 
		 	//http://hmkcode.com/android-internet-connection-using-http-get-httpclient/
		 	try {
		 		 boolean result = false;
		 
		 			result = in.isReachable(100);
		 
		 			/*if(reachable == true) 
		 			{
		 				reponse = "Reponse OK";
		 				Toast.makeText(getApplicationContext(), reponse, Toast.LENGTH_SHORT).show();
		 			} 
		 			else 
		 			{
		 				reponse = "Pas de reponse";
		 				Toast.makeText(getApplicationContext(), reponse, Toast.LENGTH_SHORT).show();
		 			}*/
		 	} 
		 	
		 	catch (IOException e)
		 	{
		 		// TODO Auto-generated catch block
		 		String nada = "";
		 	}
	 
	}
	 
	public void test()
	{
	
		 	InputStream inputStream = null;
	        String result = "";
	        
	        try {
	 
	            		HttpClient httpclient = new DefaultHttpClient();
	            		HttpResponse httpResponse = httpclient.execute(new HttpGet("www.google.fr"));
	            		//	reponse
	            		inputStream = httpResponse.getEntity().getContent();
	            		if(inputStream != null)
	            		{
	            			result = "Communication ";
	            			Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
	            		}
	            		else
	            		{
	            			result = "Did not work!";
	            			Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
	            		}
	 
	        } 
	        
	        catch (Exception e) 
	        {
	           String erreur = "plouf";
	        }
	 
		
		
	}
	 
		
	
	public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {
 
            // creation du HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // faire une requete de type GET sur l'url suivante
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
            // reception de la reponse
            inputStream = httpResponse.getEntity().getContent();
            // convertir inputstream en string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Probleme mon gars!";
 
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
 
        return result;
    }

     private static String convertInputStreamToString(InputStream inputStream) throws IOException
     {

    	 BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    	 String line = "";
    	 String result = "";

    	 while((line = bufferedReader.readLine()) != null)
    		 result += line;
    	 inputStream.close();
    	 return result;
     }


	 private class HttpAsyncTask extends AsyncTask<String, Void, String> 
	 {
	        @Override
	        protected String doInBackground(String... urls) 
	        {
	        	 
	            return GET(urls[0]);
	        }
	        // onPostExecute displays the results of the AsyncTask.
	        @Override
	        protected void onPostExecute(String result) 
	        {
	           // Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
	        	//String reponse = "Raspberry à répondu:  " +  result.toUpperCase();
	        	//reponse = "Raspberry répond aux requettes HTTP ";
	        	String reponse = "";
	        	
	            //champ_resultat.setText(result);
	           // etat  = champ_resultat.toString();
	            
	           // Toast.makeText(getApplicationContext(), 
	           //               t, Toast.LENGTH_LONG).show();
	        	
	           // champ_reception.setText(result);
	           //	String etat = "";
	        	
	            champ_reception.setText(reponse);
	            
	            //champ_reception.setText(result);
	            //etat  = champ_reception.toString();
	            
	           
	            
	            if(result.equals("on"))
 	 			  {	  
 	 				  alarm.setText("ALARME ON");
 	 				  position = true;
 	 				 Toast.makeText( getApplicationContext(), "Statut actuel", Toast.LENGTH_LONG).show();
 	 			  }	  
 	 			  else
 	 			  {	  
 	 				  alarm.setText("ALARME OFF");
 	 				  position = false;
 	 				 Toast.makeText( getApplicationContext(), "Statut actuel", Toast.LENGTH_LONG).show();
 	 			  }	 	
		            
	       }
	    }  

	 
	 private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
		 
			@Override
			protected Double doInBackground(String... params) 
			{
				postData(params[0]);
				return null;
			}
	 
			protected void onPostExecute(Double result)
			{
				//Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
				String toto ="";
			}
			
			protected void onProgressUpdate(Integer... progress)
			{
				String bidule = "";
			}
	 
			public void postData(String valueIWantToSend) 
			{
				// nouveau client Http
				HttpClient httpclient = new DefaultHttpClient();
				//HttpPost httppost = new HttpPost("http://www.analog-design.net/WORKAREA/mise_a_jour_alarme.php");
				HttpPost httppost = new HttpPost("http://damien.bruvier.free.fr/Rpi/mise_a_jour_alarme.php");
				
				try {
					// ajouter les datas
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					nameValuePairs.add(new BasicNameValuePair("HttpData", valueIWantToSend));
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	 
					// Execute une requete HTTP Post 
					HttpResponse response = httpclient.execute(httppost);
	 
				} 
				
				catch (ClientProtocolException e) 
				{
				
				} 
				
				catch (IOException e) 
				{
					
				}
			}
	 
		}

	    
	 public void capture_cameraClick()
	 {
		 int port = 8081;
         String adress ="82:234:53:234";
		 MyClientTask myClientTask = new MyClientTask(adress,port);
	     myClientTask.execute();
	     String cmd = "http://www.analog-design.net/WORKAREA/" +  nom_image;
	     Toast.makeText(xxxxxxxsysteme.this, cmd, Toast.LENGTH_SHORT).show();
         // new LoadImage().execute("http://www.analog-design.net/WORKAREA/sea.jpg");
	     new LoadImage().execute(cmd);
	 }   
	 
	 
	 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 socket = null;
		   
			  	try {
			  			socket = new Socket("82.234.53.234", 8081);
		    
			  			PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
			  			pw.println("cmd_capture_image");
		    
		    
			  			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) 
			   {
				   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) 
		  	{
		  		textResponse.setText(response);
		  		nom_image = response;
		  		super.onPostExecute(result);
		  	}
		  
	 }

	 
	 private class LoadImage extends AsyncTask<String, String, Bitmap> 
	 {
	        @Override
	        protected void onPreExecute() {
	            super.onPreExecute();
	            pDialog = new ProgressDialog(xxxxxxxsysteme.this);
	            pDialog.setMessage("Loading Image ....");
	            pDialog.show();
	 
	        }
	        protected Bitmap doInBackground(String... args) {
	             try
	             {
	                   bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
	 
	             } 
	             
	             catch (Exception e)
	             {
	                  e.printStackTrace();
	             }
	             
	             return bitmap;
	        }
	 
	        protected void onPostExecute(Bitmap image) 
	        {
	 
	             if(image != null){
	            	 capture_image.setImageBitmap(image);
	            	 pDialog.dismiss();
	              }
	             
	             else{
	 	             	pDialog.dismiss();
	 	             	Toast.makeText(xxxxxxxsysteme.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
	              }
	         }
	   }

	
	

}