package com.example.gui;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;


import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

//http://androidsrc.net/android-client-server-using-sockets-client-implementation/

public class MainActivity extends Activity {

		private Button button;
	 	private ToggleButton toggleButton1, toggleButton2;
	 	private Button btnDisplay;

	 	TextView text_reponse;
	 	EditText editTextAddress, editTextPort;
	 	Button buttonConnect, buttonClear;
	 	
	 
	 	
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_main);
		
			addListenerOnButton();
		
			editTextAddress = (EditText) findViewById(R.id.addressEditText);
			editTextPort = (EditText) findViewById(R.id.portEditText);
			buttonConnect = (Button) findViewById(R.id.connectButton);
				
			text_reponse = (TextView)findViewById(R.id.text_reponse);
	      
			buttonConnect.setOnClickListener(new OnClickListener() 
			{
	    	  
		          @Override
		          public void onClick(View arg0) 
		          {
		             //Client myClient = new Client(editTextAddress.getText().toString(), Integer.parseInt(editTextPort.getText().toString()) );
		              Client myClient = new Client(editTextAddress.getText().toString(), Integer.parseInt(editTextPort.getText().toString()), text_reponse);
		  		    
		        	//  Client myClient = new Client(text_reponse);
			            
		             myClient.execute();
		             
		            // Result aResultM =  myCkient.  task.get();  //Add this
		          }
	       });
	  
	      /* buttonClear.setOnClickListener(new OnClickListener() 
	       {
	  
		          @Override
		          public void onClick(View v) 
		          {
		             .setText("");
		          }
	       });*/
	      
	}

	@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;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	
	public void addListenerOnButton() 
	{

		toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
		toggleButton2 = (ToggleButton) findViewById(R.id.toggleButton2);
		btnDisplay = (Button) findViewById(R.id.btnDisplay);

		btnDisplay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) 
			{
				   StringBuffer result = new StringBuffer();
				   result.append("toggleButton1 : ").append(toggleButton1.getText());
				   result.append("\ntoggleButton2 : ").append(toggleButton2.getText());
				   Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
			}

		});

	  }
}

class Client extends AsyncTask<Void, Void, Void> 
{
	 
	 
	   String dstAddress;
	   int dstPort;
	   String response = "";
	   TextView textResponse;
	   
	
	 
	   Client(String addr, int port, TextView textResponse)
	   {
	      dstAddress = addr;
	      dstPort = port;
	      this.textResponse = textResponse;
	   }
	 
	   @Override
	   protected Void doInBackground(Void... arg0)
	   {
		   String st;
		      Socket socket = null;
		      //DataOutputStream dataOutputStream = null;
		      //DataInputStream dataInputStream = null;
		      
		     // PrintWriter out;
		      String data = "Toobie ornaught toobie";
		      
		      try {
			         socket = new Socket(dstAddress, dstPort);
			 
			       //send the message to the server
		          // out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
			       //  PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			      //   System.out.print("Sending string: '" + data + "'\n");
			      //   out.print(data);
		         
			        
			        // envoi 
			        PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
					pw.println("cmd");
					
					
					// retour 	  
					InputStream s1In = socket.getInputStream();
		        	DataInputStream dis = new DataInputStream(s1In);
		         	st = new String (dis.readUTF());
		   //     	  textResponse.setText(st);
		        	//System.out.println("Réponse --> : " + st);
		        	Log.d("Testing",st);
					//textmessage.setText("text");

		        	//textView1.setText("lklmk");
					//socket.close();
		        	  //response.setText("");
					

			         
			         //// 
	/*		         
			         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)
		      {
		         // 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 aaa = "46465";
		  // Toast.makeText(getApplicationContext(), "Le traitement asynchrone est terminé", Toast.LENGTH_LONG).show();
		   //showDialog("Downloaded " + result + " bytes");
	      //textResponse.setText(response);
	      super.onPostExecute(result);
		 //  Toast.makeText(getApplicationContext(), "dkjfgdklskj", Toast.LENGTH_SHORT).show();
	   }
	 
}
