package univ.lille1;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Button;
import android.widget.EditText;

/**
 * Fonction GET : classe pour le get run danc un thread qui extends AsyncTack
 *
 * 
 * @author pahouayang
 *
 */
class GetUsers extends AsyncTask<Void, Void, String> {

	public Activity activity;

	public GetUsers(Activity activity) {
		this.activity = activity;
	}

	/**
	 * change l'entity recupere en ascii
	 * 
	 * @param entity
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	protected String getASCIIContentFromEntity(HttpEntity entity)
			throws IllegalStateException, IOException {
		InputStream in = entity.getContent();
		StringBuffer out = new StringBuffer();
		int n = 1;
		while (n > 0) {
			byte[] b = new byte[4096];
			n = in.read(b);
			if (n > 0)
				out.append(new String(b, 0, n));
		}
		return out.toString();
	}

	/**
	 * utilisation du bundled http get de Apache pour recuperer les information
	 * de l'url et les met dans text
	 */
	protected String doInBackground(Void... params) {
		// url
		String uri = "http://pahoua-yang.fr/projets/android/personne.json";
		// nous sommes client
		HttpClient httpClient = new DefaultHttpClient();
		// notre context
		HttpContext localContext = new BasicHttpContext();
		// bundled http get de Apache
		HttpGet httpGet = new HttpGet(uri);
		String text = null;
		try {
			// reponce de la requete
			HttpResponse response = httpClient.execute(httpGet, localContext);
			// stok la reponse dans une entity
			HttpEntity entity = response.getEntity();
			// transforme l'entity en string
			text = getASCIIContentFromEntity(entity);
		} catch (Exception e) {
			return e.getLocalizedMessage();
		}
		return text;
	}

	/**
	 * apres de get, modification de la vue du edit text
	 */
	protected void onPostExecute(String results) {
		if (results != null) {
			// set le edit text
			EditText et = (EditText) this.activity.findViewById(R.id.my_edit);
			et.setText(results);
		}
		// remet le bouton en active
		Button b = (Button) this.activity.findViewById(R.id.my_button_get);
		b.setClickable(true);
	}

}