package com.appli.gui;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
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.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.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import android.app.AlertDialog;
import android.content.DialogInterface;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.appli.patoche.R;

public class playlist_activity 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.playlist);
		listView = (ListView) findViewById(R.id.listView1);
		
		accessWebService();
		
		// Check All
		Button btnCheckAll = (Button) findViewById(R.id.btnCheckAll);
		btnCheckAll.setOnClickListener(new OnClickListener()
		{
				public void onClick(View v) 
				{
					int count = listView.getAdapter().getCount();
					for (int i = 0; i < count; i++)
					{
						LinearLayout itemLayout = (LinearLayout)listView.getChildAt(i); 
						CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.box);
						checkbox.setChecked(true);
					}  
				}
		});
		
		 // Clear All
		Button btnClearAll = (Button) findViewById(R.id.btnClearAll);
		btnClearAll.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View v) {
				int count = listView.getAdapter().getCount();
				for (int i = 0; i < count; i++) {
					LinearLayout itemLayout = (LinearLayout)listView.getChildAt(i); // Find by under LinearLayout
					CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.box);
					checkbox.setChecked(false);
				}  
			}
		});

		
		 // CHARGER
		Button btn_load = (Button) findViewById(R.id.btn_Load);
		btn_load.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View v) 
			{
				
				chargement();
		/*		
			    ArrayList<String> array_lecture = readFile("/mnt/sdcard/play_list.txt");
				
				Toast.makeText(MainActivity.this, "Chargement ..." ,Toast.LENGTH_LONG).show();  
				
				int count = listView.getAdapter().getCount();
				for (int i = 0; i < count; i++) 
				{
					LinearLayout itemLayout = (LinearLayout)listView.getChildAt(i); 
					CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.box);
					
					
					String val = checkbox.getTag().toString();
					
					boolean q = array_lecture.contains(val);
					
					if( array_lecture.contains(val))
					{	
						checkbox.setChecked(true);
					}	
					else
					{	
						checkbox.setChecked(false);
					}	
				}  
				*/
			}
		});
		
		// SAUVER 
		// recherche les checkbox qui ont �t� coch�es
		Button btnGetItem = (Button) findViewById(R.id.btn_Save);
		btnGetItem.setOnClickListener(new OnClickListener()
		{
				public void onClick(View v)
				{
					
					showInputDialog();
					
					/*
								Toast.makeText(MainActivity.this, "Sauvegarde ..." ,Toast.LENGTH_LONG).show();  
			
								
								int count = listView.getAdapter().getCount();
								
								List<String> liste = new ArrayList<String>();
								
								for (int i = 0; i < count; i++) 
								{
									LinearLayout itemLayout = (LinearLayout)listView.getChildAt(i); 
									CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.box);
									if(checkbox.isChecked())
									{
																
										liste.add(checkbox.getTag().toString());
										//Toast.makeText(MainActivity.this,checkbox.getTag().toString() ,Toast.LENGTH_LONG).show();  
									}
								}  
								
								
								File file = new File("/mnt/sdcard/play_list.txt");
								Writer fileWriter = null;
								BufferedWriter bufferedWriter = null;
			
								try {
			
										fileWriter = new FileWriter(file);
										bufferedWriter = new BufferedWriter(fileWriter);
										String line = "";
										
										for (int k = 0; k < liste.size(); k++)
										{
											line = liste.get(k) + System.getProperty("line.separator");
											bufferedWriter.write(line);
				
											
										}
										
										bufferedWriter.close();
										
			
								} 
								catch (IOException e)
								{
									e.printStackTrace();
								}
					*/
					
				}
		});
		
		
		
		// Start
		Button btn_start = (Button) findViewById(R.id.btn_Start);
		btn_start.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View v)
			{
				final ArrayList<String> arr = new ArrayList<String>();
		        //arr.add("un.mp3");
		        //arr.add("deux.mp3");
		        //arr.add("trois.mp3");
		        //arr.add("quatre.mp3");
		        
		        int count = listView.getAdapter().getCount();
				List<String> liste = new ArrayList<String>();
				
				for (int i = 0; i < count; i++) 
				{
					LinearLayout itemLayout = (LinearLayout)listView.getChildAt(i); 
					CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.box);
					if(checkbox.isChecked())
					{
						liste.add(checkbox.getTag().toString());
					}
				}  
		        
				
				// verifier que la liste n'est pas vide !
				int n = liste.size();
				if(n == 0)
				{
		             Toast.makeText(playlist_activity.this, "La playliste est vide !" , Toast.LENGTH_LONG).show();   
				}
				else
				{	
					Intent player_Intent = new Intent(playlist_activity.this, bis_player_activity.class); 
					//Intent player_Intent = new Intent(MainActivity.this, player_activity.class);
					//player_Intent.putExtra("array_list", arr);
					//player_Intent.putExtra("name_mp3", "xyz" );
					for (int i = 0; i < n ; i++) 
					{
						  arr.add(liste.get(i));
					}
					
					player_Intent.putStringArrayListExtra("key", arr);
					startActivity(player_Intent);
				}
				
			}
		});
		
		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(playlist_activity.this, myArrList.get(position).get("Name") , Toast.LENGTH_LONG).show();   
		        	}
	    });
		
		
	}
 
	
 
	 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();
			       
			 }
 
			 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);
				
				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);	
				}
				
				listView.setAdapter(new CountryAdapter(this));
				
		 	} 
		 	
		 	catch (JSONException e) 
		 	{
		 		Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
		 	}
	 
		 	
	 }
	 
	    public class CountryAdapter extends BaseAdapter 
	    {
	        private Context context;

	        public CountryAdapter(Context c) 
	        {
	            context = c;
	        }
	 
	        public int getCount() {
	            return myArrList.size();
	        }
	 
	        public Object getItem(int position) {
	            return position;
	        }
	 
	        public long getItemId(int position) {
	            return position;
	        }
			public View getView(final int position, View convertView, ViewGroup parent) 
			{
			
				LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			 
				if (convertView == null) 
				{
					convertView = inflater.inflate(R.layout.playlist_list_item, null); 
				}
				
				TextView txtID = (TextView) convertView.findViewById(R.id.a); 
				txtID.setText(myArrList.get(position).get("CustomerID"));
				
				TextView txtCode = (TextView) convertView.findViewById(R.id.b);
				txtCode.setText(myArrList.get(position).get("Name") );
				
				CheckBox Chk = (CheckBox) convertView.findViewById(R.id.box);
				Chk.setTag(myArrList.get(position).get("Name"));
		          
		        return convertView;
					
			}

	    }

	   
	    public ArrayList<String> readFile(String filename)
		{
			 	  	File pipo = new File(filename);	
				 	ArrayList<String> myArr = new ArrayList<String>();
					
					try {
							BufferedReader br = new BufferedReader(new FileReader(pipo));
							String line;
							
							while ((line = br.readLine()) != null)
							{
								myArr.add(line);
							}
							br.close();
					} 
					
					catch (IOException e) 
					{
						e.printStackTrace();
					}
					
					return(myArr);
		}
	    
	    protected void onActivityResult(int requestCode, int resultCode, Intent data)
		{
			  
			  if(data != null && data.hasExtra("valeur_retour"))
			  {
				  //Toast.makeText(this, data.getExtras().getString("valeur_retour"), Toast.LENGTH_SHORT).show();
				  
				  String fichier = data.getExtras().getString("valeur_retour");
				  ArrayList<String> array_lecture = readFile("/mnt/sdcard/" + fichier);
					
			      //Toast.makeText(MainActivity.this, "Chargement ..." ,Toast.LENGTH_LONG).show();  
					
					int count = listView.getAdapter().getCount();
					for (int i = 0; i < count; i++) 
					{
						LinearLayout itemLayout = (LinearLayout)listView.getChildAt(i); 
						CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.box);
						
						
						String val = checkbox.getTag().toString();
						
						boolean q = array_lecture.contains(val);
						
						if( array_lecture.contains(val))
						{	
							checkbox.setChecked(true);
						}	
						else
						{	
							checkbox.setChecked(false);
						}	
					}  
					
				  
				  
				 
				 			  
				  ActionBar ab = getActionBar();
				  String titre = "Utils01:  " + fichier; 
				  ab.setTitle(titre);
			    
			  }
		} 

	    
	    protected void chargement()
	    {
	    	Intent intent = new Intent(this, playlist_files_activity.class);
			startActivityForResult(intent, 0);
	    }
	    
	    protected void showInputDialog()
	    {
			LayoutInflater layoutInflater = LayoutInflater.from(playlist_activity.this);
			View promptView = layoutInflater.inflate(R.layout.playlist_dialog_save, null);
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(playlist_activity.this);
			alertDialogBuilder.setView(promptView);

			final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
			
			alertDialogBuilder.setTitle("This is list choice dialog box");
			
			alertDialogBuilder.setPositiveButton("Save",new DialogInterface.OnClickListener() 
	        {
	                @Override
	                public void onClick(DialogInterface dialog, int which)
	                {
	                		String fileName = editText.getText().toString() +".txt";
	                        int count = listView.getAdapter().getCount();
							List<String> liste = new ArrayList<String>();
							
							for (int i = 0; i < count; i++) 
							{
								LinearLayout itemLayout = (LinearLayout)listView.getChildAt(i); 
								CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.box);
								if(checkbox.isChecked())
								{
															
									liste.add(checkbox.getTag().toString());
								}
							}  
							
							File file = new File("/mnt/sdcard/" + fileName);
							Writer fileWriter = null;
							BufferedWriter bufferedWriter = null;
		
							try {
		
									fileWriter = new FileWriter(file);
									bufferedWriter = new BufferedWriter(fileWriter);
									String line = "";
									
									for (int k = 0; k < liste.size(); k++)
									{
										line = liste.get(k) + System.getProperty("line.separator");
										bufferedWriter.write(line);
			
										
									}
									
									bufferedWriter.close();
									
		
							} 
							catch (IOException e)
							{
								e.printStackTrace();
							}
		
	                        
	                }
	        });
	 
			alertDialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() 
	        {
	                @Override
	                public void onClick(DialogInterface dialog, int which) {
	                    dialog.cancel();
	                }
	        });
	 
			alertDialogBuilder.show();
			
		}
	 
}
