package com.button;

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 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;
 
public class MainActivity extends Activity {
	 
	
	private boolean position = false;
	private String message = "";
	
	Button alarm;
	TextView champ_connexion;
	TextView champ_reception;
 
	public void onCreate(Bundle savedInstanceState) 
	{
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
				
		alarm = (Button) findViewById(R.id.button_commande);
		// chargement de la configuration
		alarm.setText("OFF");
		
		champ_connexion = (TextView) findViewById(R.id.champ_connexion);
		champ_reception = (TextView) findViewById(R.id.champ_reception);
       
   	 	if(isConnected())
   	 	{
   	 		champ_connexion.setBackgroundColor(0xFF00CC00);
   	 		champ_connexion.setText("Connexion réseau");
   	 	}
   	 	else
   	 	{
   	 		champ_connexion.setText("Probléme avec le réseau");
   	 	}      
		
		
		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 = "Pas d'alarme"; 
   	 				  new MyAsyncTask().execute("off");	
   	 
   	 			  }	 	  
   	 			  
   	 		     Toast.makeText(getApplicationContext(), 
   	                          message, Toast.LENGTH_LONG).show();
   	 
   	 		  }
   	 	});
		
		
		//new HttpAsyncTask().execute("http://analog-design.net/WORKAREA/script.php");
		new HttpAsyncTask().execute("http://analog-design.net/WORKAREA/lire_etat_alarme.php");
		
	}
	
	
	 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 static String GET(String url)
     {
    	 InputStream inputStream = null;
    	 String result = "";

    	 try {

    		 	// create HttpClient
    		 	HttpClient httpclient = new DefaultHttpClient();

    		 	// make GET request to the given URL
    		 	HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

    		 	// receive response as inputStream
    		 	inputStream = httpResponse.getEntity().getContent();

    		 	// convert inputstream to string
    		 	if(inputStream != null)
    		 		result = convertInputStreamToString(inputStream);
    		 	else
    		 		result = "Did not work!";
    		} 
    	 
    	 	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 ";
	        	
	        	
	            //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;
 	 			  }	  
 	 			  else
 	 			  {	  
 	 				  alarm.setText("ALARME OFF");
 	 				  position = false;
 	 			  }	 	
		            
	       }
	    }  

	 
	 private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
		 
			@Override
			protected Double doInBackground(String... params) 
			{
				// TODO Auto-generated method stub
				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) 
			{
				// Create a new HttpClient and Post Header
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://www.analog-design.net/WORKAREA/mise_a_jour_alarme.php");
	 
				try {
					// Add your data
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					nameValuePairs.add(new BasicNameValuePair("HttpData", valueIWantToSend));
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	 
					// Execute HTTP Post Request
					HttpResponse response = httpclient.execute(httppost);
	 
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
				} catch (IOException e) {
					// TODO Auto-generated catch block
				}
			}
	 
		}

	    
	   
	
	
}