package com.example.asynctask03;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
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

// media player good
//http://o7planning.org/web/fe/default/en/document/1649538/android-mediaplayer-and-videoview-tutorial

//http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/

//http://code.tutsplus.com/fr/tutorials/create-a-music-player-on-android-project-setup--mobile-22764

//https://www.hrupin.com/2010/12/simple-android-mp3-media-player

public class MainActivity extends Activity
{

	private String totostr;
	private String url = "http://www.analog-design.net/MP3/json02.php";     //android.php";
	private ListView listView;
 
	
	ArrayList<HashMap<String, String>> myArrList = new ArrayList<HashMap<String, String>>();
	 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView = (ListView) findViewById(R.id.listView1);
		
		accessWebService();
		
		
		listView.setOnItemClickListener(new OnItemClickListener() 
	    {
					@Override
		         	public void onItemClick(AdapterView<?> a, View v, int position, long id)
					{
						 Map<String, String> tg = myArrList.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();
			             
			             
			             System.out.println(myArrList.get(position).get("Name"));
			           Toast.makeText(MainActivity.this, myArrList.get(position).get("Name") , Toast.LENGTH_LONG).show();   
							 
			            // Toast.makeText(MainActivity.this, bbb , Toast.LENGTH_LONG).show();   
						
			            Intent player_Intent = new Intent(MainActivity.this, test.class);
					  	 player_Intent.putExtra("name_mp3", myArrList.get(position).get("Name") );
				         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);
				            	}
				                
				            }
				        }
						*/
						
		
						
					
		        		
		        	}
	    });
		
		
	}
 
	 @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)
		 {
			 URL url;
   
			 try
			 {
				 
				 	url = new URL("http://www.analog-design.net/MP3/json02.php");
			        BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream()));

			        StringBuilder str = new StringBuilder();
			        String line;
			        while ((line = in.readLine()) != null)
			        	str.append(line);
			        in.close();
				 
			        totostr = str.toString();
			        /*
			        [{"CustomerID":"C001","Name":"Win Weerachai","Email":"win.weerachai@thaicreate.com","CountryCode":"TH","Budget":"1000000","Used":"600000"},
			         {"CustomerID":"C002","Name":"John Smith","Email":"john.smith@thaicreate.com","CountryCode":"UK","Budget":"2000000","Used":"800000"},
			         {"CustomerID":"C003","Name":"Jame Born","Email":"jame.born@thaicreate.com","CountryCode":"US","Budget":"3000000","Used":"600000"},
			         {"CustomerID":"C004","Name":"Chalee Angel","Email":"chalee.angel@thaicreate.com","CountryCode":"US","Budget":"4000000","Used":"100000"}]
			         */
			        
			        //{"elo_affectation":[{"joueur":"marek","elo":"1050"},{"joueur":"henrique","elo":"1300"},{"joueur":"fabien","elo":"1300"},{"joueur":"dominique","elo":"1100"},{"joueur":"remy","elo":"1100"},{"joueur":"stephaner","elo":"1000"},{"joueur":"laurent","elo":"1200"},{"joueur":"damien","elo":"1000"},{"joueur":"franckdc","elo":"1000"},{"joueur":"franckv","elo":"1000"},{"joueur":"thierry","elo":"1000"},{"joueur":"amokrane","elo":"1050"},{"joueur":"olivier","elo":"1250"},{"joueur":"stephaneb","elo":"1000"},{"joueur":"patrick","elo":"1000"},{"joueur":"bertrand","elo":"950"},{"joueur":"emile","elo":"850"},{"joueur":"joel","elo":"950"},{"joueur":"alexandre","elo":"750"}]}
			        
			       
			 }
 
			 catch (Exception  e)
			 {
				 e.printStackTrace();
			 } 
			 
			 
			 
			 return null;
		 }
 
		
  
		 @Override
		 protected void onPostExecute(String result) 
		 {
			 ListDrwaer();
		 }
	 }
 
	 
	 public void accessWebService() 
	 {
		 JsonReadTask task = new JsonReadTask();
		 task.execute(new String[] { url });
	 }
 
	 public void ListDrwaer()
	 {
		 	try
		 	{
		 		JSONArray data = new JSONArray(totostr);
				
				//ArrayList<HashMap<String, String>> myArrList = new ArrayList<HashMap<String, String>>();
				HashMap<String, String> map;
				
				for(int i = 0; i < data.length(); i++){
			            JSONObject c = data.getJSONObject(i);
			  			map = new HashMap<String, String>();
			  			map.put("CustomerID", c.getString("CustomerID"));
			  			map.put("Name", c.getString("Name"));
			  			map.put("Email", c.getString("Email"));
			  			map.put("CountryCode", c.getString("CountryCode"));
			  			map.put("Budget", c.getString("Budget"));
			  			map.put("Used", c.getString("Used"));
			  			myArrList.add(map);	
				}
				
				
				// SimpleAdapter simpleAdapter = new SimpleAdapter(this, myArrList, android.R.layout.simple_list_item_1, from, to);
				SimpleAdapter simpleAdapter = new SimpleAdapter(this, myArrList, R.layout.list_item, new String[] { "CustomerID" , "Name" , "Email", "Used"}, new int[] { R.id.a, R.id.b, R.id.c , R.id.d });
					 	listView.setAdapter(simpleAdapter);
				
		 	} 
		 	
		 	catch (JSONException e) 
		 	{
		 		Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
		 	}
	 
		 	
	 }
 
	
	 
}