package com.alarm;


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;


public class commande extends Activity {
	 
	private TextView switchStatus;
	 private Switch mySwitch;
	 String etat = "";
	 boolean flag = false;
	 
	 TextView champ_resultat;
	 TextView champ_connexion;
		
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.commande);
        
        champ_connexion = (TextView) findViewById(R.id.champ_connexion);
        champ_resultat = (TextView) findViewById(R.id.champ_resultat);
       
   	 	if(isConnected())
   	 	{
   	 		champ_connexion.setBackgroundColor(0xFF00CC00);
   	 		champ_connexion.setText("Connexion rseau");
   	 	}
   	 	else
   	 	{
   	 		champ_connexion.setText("Problme avec le rseau");
   	 	}      
        
   	 	
   		new HttpAsyncTask().execute("http://analog-design.net/WORKAREA/lire_etat_alarme.php");
        
    	
        switchStatus = (TextView) findViewById(R.id.switchStatus);
        mySwitch = (Switch) findViewById(R.id.mySwitch);
       
//set the switch to ON 
// mySwitch.setChecked(true);
  
        //attach a listener to check for changes in state
        mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
       
         @Override
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
         {
       	  Toast.makeText(getBaseContext(), "Update ....", Toast.LENGTH_LONG).show();

       	     	if(flag == true)
       	     	{
       	     		if(isChecked)
        	 	   	 {
       	     			switchStatus.setText("Alarm ON");
       	     			new MyAsyncTask().execute("on");		
        	 	   	 }
       	     		else
       	     		{
       	     			switchStatus.setText("Alarme OFF");
       	     			new MyAsyncTask().execute("off");	
       	     		}
       	     	}
         }
        });
        
        
	   
         
//        String aqw = champ_resultat.getText().toString();
        //check the current state before we display the screen
//        Toast.makeText(getBaseContext(), aqw, Toast.LENGTH_LONG).show();
        
        
/*        if(etat.equals("off"))
        {
        	mySwitch.setChecked(false);
        }
        else
        {
        	mySwitch.setChecked(true);
        }
        
/*        if(mySwitch.isChecked())
        {
        	switchStatus.setText("Switch is currently ON");
        	 new MyAsyncTask().execute("alpha");		
        }
        else 
        {
        	switchStatus.setText("Switch is currently OFF");
        	 new MyAsyncTask().execute("beta");	
        }
*/    
    }
    
    
    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 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
			}
		}
 
	}

    
    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();
            champ_resultat.setText(result);
            etat  = champ_resultat.toString();
            
          //  Toast.makeText(getBaseContext(), full, Toast.LENGTH_LONG).show();
            
            if(etat.equals("off"))
            {
            	mySwitch.setChecked(false);
            	  Toast.makeText(getBaseContext(), "offffff", Toast.LENGTH_LONG).show();
            }
            else
            {
            	mySwitch.setChecked(true);
            	  Toast.makeText(getBaseContext(), "onnnnnnn", Toast.LENGTH_LONG).show();
            }
            
       }
    }
    
   
    
    /*****************************************************/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
}