package com.example.utils01;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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 android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
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;
 
//http://www.tutomobile.fr/personnaliser-une-listview-tutoriel-android-n%C2%B07/04/07/2010/


public class ListMp3_activity extends Activity 
{
 
	private ListView maListViewPerso;
	private Context context;
	 String lolo;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.liste_mp3);
        
        context=this;
 
        maListViewPerso = (ListView) findViewById(R.id.listviewperso);
        
        
        //webserver tyu = new webserver();
        //tyu.titi();
        
        
        //new HttpAsyncTask().execute("http://www.analog-design.net/MP3/listing.php");
        new TCP().execute("http://www.analog-design.net/MP3/listing.php");
    	Toast.makeText(getApplicationContext(), lolo, Toast.LENGTH_LONG).show();
        
        //String serverResponse = apiObj.execute(nameValuePairs).get();
        
        //HttpAsyncTask get
        lolo ="messager";
        
        // copier le fichier dans la sdcard
        new url().execute("http://www.analog-design.net/MP3/listing.txt");
    
        // on lit le fichier
        FileDemo instance = new FileDemo(this);
        String root_sd = Environment.getExternalStorageDirectory().toString();
        ArrayList<String> myArr = instance.eadFile(root_sd + "/listing_musique.txt");
 
        // preparation
        
        ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
        
        HashMap<String, String> map;
        
        int l= myArr.size();
        for (int i = 0; i < l; i++)
        {	
        		map = new HashMap<String, String>();
        		String element = myArr.get(i);
        		String result = element.substring(0, element.lastIndexOf("."));
        		
        		map.put("titre", element.substring(0, element.lastIndexOf(".")));
        		map.put("description", "blabla");
        		map.put("img", String.valueOf(R.drawable.mp3));
        		listItem.add(map);
        }
        
        
        
        map = new HashMap<String, String>();
        map.put("titre", "xyz");
        map.put("description", "blabla");
        //on insère la référence à l'image (convertit en String car normalement c'est un int) que l'on récupérera dans l'imageView créé dans le fichier affichageitem.xml
        map.put("img", String.valueOf(R.drawable.mp3));
        listItem.add(map);
 
       /// on repete
 
        map = new HashMap<String, String>();
        map.put("titre", "b");
        map.put("description", "blabla");
        map.put("img", String.valueOf(R.drawable.mp3));
        listItem.add(map);
 
        map = new HashMap<String, String>();
        map.put("titre", "c");
        map.put("description", "blabla");
        map.put("img", String.valueOf(R.drawable.mp3));
        listItem.add(map);
 
        map = new HashMap<String, String>();
        map.put("titre", "d");
        map.put("description", "titititata");
        map.put("img", String.valueOf(R.drawable.mp3));
        listItem.add(map);
 
        //Création d'un SimpleAdapter qui se chargera de mettre les items présent dans notre list (listItem) dans la vue affichageitem
        SimpleAdapter mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.item_mp3,
               new String[] {"img", "titre", "description"}, new int[] {R.id.img, R.id.titre, R.id.description});
 
        //On attribut à notre listView l'adapter que l'on vient de créer
        maListViewPerso.setAdapter(mSchedule);
 
        //écouteur d'évènement sur notre listView

        maListViewPerso.setOnItemClickListener(new OnItemClickListener() 
        {
				@Override
	        	@SuppressWarnings("unchecked")
	         	public void onItemClick(AdapterView<?> a, View v, int position, long id)
				{
					//on récupère la HashMap contenant les infos de notre item (titre, description, img)

					HashMap<String, String> map = (HashMap<String, String>) maListViewPerso.getItemAtPosition(position);
/*	
	        		AlertDialog.Builder adb = new AlertDialog.Builder(ListMp3_activity.this);
	        		adb.setTitle("Sélection Item");
	        		adb.setMessage("Votre choix : "+map.get("titre"));
	        		adb.setPositiveButton("Ok", null);
	        		adb.show();
*/	        		
					
					Intent player_Intent = new Intent(ListMp3_activity.this, PlayerActivity.class);
					
					player_Intent.putExtra("name_mp3", map.get("titre") );
					
		            startActivity(player_Intent);
	        		
	        	}
         });
 
    }
    
    // classe interne
    class TCP extends AsyncTask<String, Void, String>
    {
    	
    	private void processValue(String myValue) 
	    {
	       //handle value 
	       //Update GUI, show toast, etc..
    		 ListMp3_activity.this.lolo= "result";
	    } 
	
    	
    	@Override
        protected String doInBackground(String... urls)
        {
            
            InputStream inputStream = null;
            String result = "";
            try {
     
            	// create HttpClient
                HttpClient httpclient = new DefaultHttpClient();
     
                // make GET request to the given URL
                HttpResponse httpResponse = httpclient.execute(new HttpGet(urls[0]));
     
                // receive response as inputStream
                inputStream = httpResponse.getEntity().getContent();
                	
                BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
                String line = "";
               
                while((line = bufferedReader.readLine()) != null)
                    result += line;
         
                inputStream.close();
                	
                	
               
     
            } catch (Exception e) {
                Log.d("InputStream", e.getLocalizedMessage());
            }
     
            return result;
            
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result)
        {
            //Toast.makeText(, "Received!", Toast.LENGTH_LONG).show();
            Log.d("InputStream", result);
            processValue(result);
            
            
           // ListMp3_activity.this.lolo= "result";
       }
    }
    
    
}

//http://hmkcode.com/android-parsing-json-data/
//http://hmkcode.com/android-internet-connection-using-http-get-httpclient/

//http://instinctcoder.com/android-studio-asynctask-return-value-to-caller

class HttpAsyncTask extends AsyncTask<String, Void, String>
{
	
	 /*private void processValue(String myValue) 
	    {
	       //handle value 
	       //Update GUI, show toast, etc..
	    } 
	*/
	
	
	
    @Override
    protected String doInBackground(String... urls)
    {
        
        InputStream inputStream = null;
        String result = "";
        try {
 
        	// create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
 
            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(urls[0]));
 
            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
            	
            BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
            String line = "";
           
            while((line = bufferedReader.readLine()) != null)
                result += line;
     
            inputStream.close();
            	
            	
           
 
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
 
        return result;
        
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result)
    {
        //Toast.makeText(, "Received!", Toast.LENGTH_LONG).show();
        Log.d("InputStream", result);
        //processValue(result);
       
   }
    
    
    
    
   
}