package com.camera.simplemjpeg;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
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 org.apache.http.util.ByteArrayBuffer;

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.widget.ToggleButton;
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 com.camera.simplemjpeg.flux_camera.communication_start;

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 gpio extends Activity
{
	
	Button cmd;
	TextView resultat;
	TextView textMsg, textPrompt;
 	Switch switch_gpio;
 	ToggleButton toggleButton1, toggleButton2;
	
	public void onCreate(Bundle savedInstanceState) 
	{
		
			super.onCreate(savedInstanceState);
			setContentView(R.layout.gpio);
			
			ActionBar actionBar = getActionBar();
			actionBar.show();
			
			cmd=(Button) findViewById(R.id.button_cmd);
			resultat=(TextView) findViewById(R.id.text_resultat);
			textMsg = (TextView)findViewById(R.id.textmsg);
			textPrompt = (TextView)findViewById(R.id.textprompt);
			switch_gpio = (Switch) findViewById(R.id.switch_gpio);
			toggleButton1 = (ToggleButton) findViewById(R.id.toggle1);
		
			cmd.setOnClickListener(new OnClickListener() 
			{
				public void onClick(View v)
				{
				    textMsg.setText("dfsfsdfskdfsdlgfsdglsglslgsd");		
					new CommandTask().execute("tag_allume_led");
				}
			});
		
		
			switch_gpio.setChecked(true);
			switch_gpio.setOnCheckedChangeListener(new OnCheckedChangeListener()
			{

				@Override
			   	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
				{
					    if(isChecked)
					    {
					    	Toast.makeText(getBaseContext(), "OFF", Toast.LENGTH_SHORT).show();
					    }
					    else
					    {
					    	Toast.makeText(getBaseContext(), "ON", Toast.LENGTH_SHORT).show();
					    }
			   }
			});
		  
		 
		  if(switch_gpio.isChecked())
		  {
			  Toast.makeText(getBaseContext(), "ON", Toast.LENGTH_SHORT).show();
		  }
		  else 
		  {
			  Toast.makeText(getBaseContext(), "OFF", Toast.LENGTH_SHORT).show();

		  }
		  
		  toggleButton1.setOnClickListener(new View.OnClickListener() 
		  {
				      public void onClick(View v)
				      {
					    	String etat = "";  
					    	  
					        if (((ToggleButton) v).isChecked())
					        {	
					        	 Toast.makeText(getApplicationContext(), "Toggle is on", Toast.LENGTH_SHORT).show();
					        	 etat = "1";
					        } 	 
					        else
					        {	
					        	 Toast.makeText(getApplicationContext(), "OFFFFFFFFFFFFFFFFF", Toast.LENGTH_SHORT).show();
					        	 etat = "0";
					        }	 
					        
					       
					        String champ = "cmd_gpio" + "-" +  "17" + "-" + etat;
					        //List<String> myList = new ArrayList<String>(Arrays.asList(status.split("-")));
					        communication_gpio instance = new communication_gpio("82.234.53.234", 8080, champ);
						    instance.execute();
				      }
		  });
		
		
	}
	
	@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,MjpegActivity.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;	
	    		
		    		
	    	}
	    	
	    	return true;
    	
    }	
    
    /***************************************************************************************/
    
    class CommandTask extends AsyncTask<String, Integer, String>
    {

		@Override
		protected String doInBackground(String... params)
		{
			
			String res = PostData(params);
			return res;
		}
		
		@Override
		protected void onPostExecute(String result) 
		{
			//progressBar.setVisibility(View.GONE);
			textMsg.setText(result);
	
		}
    	
    }
/*
    class ExecuteTask extends AsyncTask<String, Integer, String>
    {

		@Override
		protected String doInBackground(String... params)
		{
			
			String res=PostData(params);
			return res;
		}
		
		@Override
		protected void onPostExecute(String result) 
		{
			//progressBar.setVisibility(View.GONE);
			resultat.setText(result);
			Toast.makeText(getApplicationContext(), result, 3000).show();
		}
    	
    }
*/
    public String PostData(String[] valeur)
    {	
    	String s="";
		/*try
		{
			HttpClient httpClient=new DefaultHttpClient();
			HttpPost httpPost=new HttpPost("http://82.234.53.234//test.php");
			//HttpPost httpPost=new HttpPost("http://analog-design.net/WORKAREA/test.php");
			
			
			int l = valeur.length;
			String str = "+++++++" + Integer.toString(l) + "+++++++++";
			System.out.println(str);
			
			List<NameValuePair> list=new ArrayList<NameValuePair>();
			list.add(new BasicNameValuePair("valeur", valeur[0]));
			
			//list.add(new BasicNameValuePair("name", valeur[0]));
			//list.add(new BasicNameValuePair("pass",valeur[1]));
			httpPost.setEntity(new UrlEncodedFormEntity(list));
		    HttpResponse httpResponse=	httpClient.execute(httpPost);
		
		    HttpEntity httpEntity=httpResponse.getEntity();
		    s= readResponse(httpResponse);
	
		}

		catch(Exception exception) 	{}
		*/
    	
    	URL textUrl;
		String textSource = "http://82.234.53.234/echange.txt";
		
		try {
			   StringBuilder content = new StringBuilder();
			
			   textUrl = new URL(textSource);
			   URLConnection ucon = textUrl.openConnection();
			   
			   BufferedReader in = new BufferedReader(new InputStreamReader( ucon.getInputStream()));
			   String inputLine;
			   while ((inputLine = in.readLine()) != null) 
			   {
				   content.append(inputLine + "\n");
			   }
			   in.close();
			   
			  // textMsg.setText(content.toString());
			   
			   File file = new File("sdcard/store.txt");
			   String url_adresse = "http://82.234.53.234/store.txt";
			   
			   URL url = new URL(url_adresse);
			   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			   urlConnection.setRequestMethod("GET");
			   urlConnection.setDoOutput(true); 
			   urlConnection.connect();
			   
			  
			   FileOutputStream fileOutput = new FileOutputStream(file);
			   InputStream inputStream = urlConnection.getInputStream();
			   int totalSize = urlConnection.getContentLength();
			   
			   int downloadedSize = 0;

			  
			   byte[] buffer = new byte[1024];
			   int bufferLength = 0; 
			   
			   while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
			   {
				    //add the data in the buffer to the file in the file output stream (the file on the sd card
				    fileOutput.write(buffer, 0, bufferLength);
				    //add up the size so we know how much is downloaded
				    downloadedSize += bufferLength;
				    //this is where you would do something to report the prgress, like this maybe
				    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;

			  }
			   
			   fileOutput.close();
			   String filepath=null;
			   
			   if(downloadedSize==totalSize)   filepath=file.getPath();
			   
			   file_operations fop = new file_operations();
	           s = fop.read("store.txt");
			  
	           //textMsg.setText("text");		
	           
			   /*InputStream is = ucon.getInputStream();
               BufferedInputStream bis = new BufferedInputStream(is);
               ByteArrayBuffer baf = new ByteArrayBuffer(50);
               int current = 0;
               while ((current = bis.read()) != -1) {
                       baf.append((byte) current);
               }
			   
               File file = new File("fileName");
               
               FileOutputStream fos = new FileOutputStream(file);
               fos.write(baf.toByteArray());
               fos.close();
               
			   BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
			   String StringBuffer;
			   String stringText = "";
			   while ((StringBuffer = bufferReader.readLine()) != null) 
			   {
				   stringText += StringBuffer;
			   }
			         bufferReader.close();
			         textMsg.setText(stringText);
			   */      
			         
			         
		} 
		
		catch (MalformedURLException e) 
		{
			   // TODO Auto-generated catch block
			   e.printStackTrace();
			   textMsg.setText(e.toString());
		} 
		
		catch (IOException e) 
		{
			   // TODO Auto-generated catch block
			   e.printStackTrace();
			   textMsg.setText(e.toString());
		}
    	
    	
		return s;

    }

    public String readResponse(HttpResponse res) 
	{
		InputStream is=null; 
		String return_text="";
		try 
		{
			is=res.getEntity().getContent();
			BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
			String line="";
			StringBuffer sb=new StringBuffer();
			while ((line=bufferedReader.readLine())!=null)
			{
				sb.append(line);
			}
			return_text=sb.toString();
		} 
		
		catch (Exception e)
		{
			
		}
		
		return return_text;
		
	}
    
    /********* envoi une commande ************/
    public class communication_gpio extends AsyncTask<Void, Void, Void> 
	{
		  
		  String dstAddress;
		  int dstPort;
		  String response = "";
		  String cmd = "";
		  
		  communication_gpio(String addr, int port, String champ)
		  {
			  dstAddress = addr;
			  dstPort = port;
			  cmd = champ;
		  }

		  @Override
		  protected Void doInBackground(Void... arg0)
		  {
		   
			  		Socket socket = null;
		   
			  		try {
			  				socket = new Socket(dstAddress, dstPort);
			  				BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			  				PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
			  				pw.println(cmd);
			  				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) 
		  {
			  	super.onPostExecute(result);
		  }
		  
	}		
	

	
	

}