package com.example.asynctask02;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
 
//https://openclassrooms.com/forum/sujet/android-list-view

public class MainActivity extends Activity
{

	private String jsonResult;
	private String url = "http://www.analog-design.net/MP3/android.php";
	private ListView listView;
 
	List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
	 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView = (ListView) findViewById(R.id.listView1);
		
		//List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
		 
		
		accessWebService();
		
		
		listView.setOnItemClickListener(new OnItemClickListener() 
	    {
					@Override
		         	public void onItemClick(AdapterView<?> a, View v, int position, long id)
					{
						 Map<String, String> tg = employeeList.get(position);
					     Set set=tg.entrySet();
					     Iterator iter = set.iterator();
				         Map.Entry me = (Map.Entry)iter.next();
					     // System.out.print(me.getKey() + ": ");
					     // System.out.println(me.getValue());
					     String aaa =(String) me.getKey();
			             String bbb = (String) me.getValue();
			             Toast.makeText(MainActivity.this, bbb , Toast.LENGTH_LONG).show();   
						
			           // Intent player_Intent = new Intent(MainActivity.this, testActivity.class);
					  //	 player_Intent.putExtra("name_mp3", bbb );
				       //  startActivity(player_Intent);
			             
/*	  OK  valide  	*/		
  
  		
						for (int i = 0 ; i < employeeList.size() ; i++) 
				        {
				            Map<String, String> myMap = employeeList.get(i);
				            
				            System.out.println("Data For Map" + i);
				            for (Entry<String, String> entrySet : myMap.entrySet())
				            {
				            	if(i == position)
				            	{	
				                //System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
				                aaa = entrySet.getKey();
				                bbb = entrySet.getValue();
				                
				                Toast.makeText(MainActivity.this, bbb , Toast.LENGTH_LONG).show();
				                
				                Log.d("Testing", aaa + " **********  " + bbb);
				            	}
				                
				            }
				        }
						
						
			//			int taille = employeeList.size();
			//	 employeeList.get(position).   .get(position);
						
			//			String conv = Integer.toString(position);
						
			//			  Toast.makeText(MainActivity.this, conv , Toast.LENGTH_LONG).show();
	
			//			HashMap<String, String> aamap = (HashMap<String, String>) listView.getItemAtPosition(position);
						
			//			String aqw = aamap.get("titre") ;
						
					
		        		
		        	}
	    });
		
	}
 
	 @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;
	 }
 
	 // Async Task to access the web
	 private class JsonReadTask extends AsyncTask<String, Void, String>
	 {
		 @Override
		 protected String doInBackground(String... params)
		 {
			 HttpClient httpclient = new DefaultHttpClient();
			 HttpPost httppost = new HttpPost(params[0]);
   
			 try
			 {
				 HttpResponse response = httpclient.execute(httppost);
				 jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
			 }
 
			 catch (ClientProtocolException e)
			 {
				 e.printStackTrace();
			 } 
			 
			 catch (IOException e) 
			 {
				 e.printStackTrace();
			 }
			 
			 return null;
		 }
 
		 private StringBuilder inputStreamToString(InputStream is) 
		 {
			 String rLine = "";
			 StringBuilder answer = new StringBuilder();
			 BufferedReader rd = new BufferedReader(new InputStreamReader(is));
 
			 try 
			 {
				 while ((rLine = rd.readLine()) != null)
				 {
					 answer.append(rLine);
				 }
			 }
 
			 catch (IOException e)
			 {
				 // e.printStackTrace();
				 Toast.makeText(getApplicationContext(), "Error..." + e.toString(), Toast.LENGTH_LONG).show();
			 }
   
			 return answer;
		 }
 
  
		 @Override
		 protected void onPostExecute(String result) 
		 {
			 ListDrwaer();
		 }
	 }
	 // end async task
 
	 
	 public void accessWebService() 
	 {
		 JsonReadTask task = new JsonReadTask();
		 // passes values for the urls string array
		 task.execute(new String[] { url });
	 }
 
	 // build hash set for list view
	 public void ListDrwaer()
	 {
		 	//List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
	 
		 	try
		 	{
		 		JSONObject jsonResponse = new JSONObject(jsonResult);
		 		JSONArray jsonMainNode = jsonResponse.optJSONArray("elo_affectation");
	 
		 		for (int i = 0; i < jsonMainNode.length(); i++) 
		 		{
				    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
				    String name = jsonChildNode.optString("joueur");
				    String number = jsonChildNode.optString("elo");
				    String outPut = name + "-" + number;
				    employeeList.add(createEmployee("employees", outPut));
		 		}
		 	} 
		 	
		 	catch (JSONException e) 
		 	{
		 		Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
		 	}
	 
		 	SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
		 	android.R.layout.simple_list_item_1, new String[] { "employees" }, new int[] { android.R.id.text1 });
		 	listView.setAdapter(simpleAdapter);
	 }
 
	 private HashMap<String, String> createEmployee(String name, String number)
	 {
		 HashMap<String, String> employeeNameNo = new HashMap<String, String>();
		 employeeNameNo.put(name, number);
		 return employeeNameNo;
	 }
	 
}