package com.example.asynctask04;


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.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.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.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
 

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.main);
		listView = (ListView) findViewById(R.id.listView1);
		
		accessWebService();
		
		
		listView.setOnItemClickListener(new OnItemClickListener() 
	    {
					@Override
		         	public void onItemClick(AdapterView<?> a, View v, int position, long id)
					{
						Toast.makeText(MainActivity.this, "********" , Toast.LENGTH_LONG).show(); 
						/*
						 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(); */  
		        	}
	    });
		
		
		
		Button btnCheckAll = (Button) findViewById(R.id.btnCheckAll);
		btnCheckAll.setOnClickListener(new OnClickListener()
		{
				public void onClick(View v) 
				{
					//Toast.makeText(MainActivity.this, "ALLLLL" , Toast.LENGTH_LONG).show();   
					
					
					
					//Toast.makeText(MainActivity.this, "ALLLLL" , 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);
						//checkbox.setChecked(true);
					}  
				}
				
		});
		
		
		Button btnClearAll = (Button) findViewById(R.id.btnClearAll);
		btnClearAll.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View v)
			{
				Toast.makeText(MainActivity.this, "CLEAR" , 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);
					checkbox.setChecked(false);
				}  */
				
			}
		});
		
	
		Button btnGetItem = (Button) findViewById(R.id.btnGetItem);
		btnGetItem.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);
					if(checkbox.isChecked())
					{
						Log.d("Item "+String.valueOf(i), checkbox.getTag().toString());
						
						Toast.makeText(MainActivity.this,checkbox.getTag().toString() ,Toast.LENGTH_LONG).show();  
					}
				}  
			}
		});

        

		
		
	}
 
	 @Override
	 public boolean onCreateOptionsMenu(Menu menu) 
	 {
		 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();
				 }
	 
				 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);
					 	
					 	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) 
	        {
	        	//super( c, R.layout.activity_column, R.id.rowTextView, );
	        	// TODO Auto-generated method stub
	            context = c;
	        }
	 
	        public int getCount() {
	        	// TODO Auto-generated method stub
	            return myArrList.size();
	        }
	 
	        public Object getItem(int position) {
	        	// TODO Auto-generated method stub
	            return position;
	        }
	 
	        public long getItemId(int position) {
	        	// TODO Auto-generated method stub
	            return position;
	        }
			public View getView(final int position, View convertView, ViewGroup parent) {
				// TODO Auto-generated method stub
				
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			 
				if (convertView == null) {
					convertView = inflater.inflate(R.layout.deux, null); 
					
				}
				
				
			//	"CustomerID" , "Name" , "Email", "Used"
				
				
				TextView txt1 = (TextView) convertView.findViewById(R.id.a); 
				txt1.setText(myArrList.get(position).get("CustomerID") + " bilou");
				
				
				TextView txt2 = (TextView) convertView.findViewById(R.id.b);
				txt2.setText(myArrList.get(position).get("Name"));
				
				TextView txt3 = (TextView) convertView.findViewById(R.id.c);
				txt3.setText(myArrList.get(position).get("Email"));
				

				TextView txt4 = (TextView) convertView.findViewById(R.id.d);
				txt4.setText(myArrList.get(position).get("Used"));

				
				CheckBox Chk = (CheckBox) convertView.findViewById(R.id.Box);
				Chk.setTag(myArrList.get(position).get("Name"));
		          
		        return convertView;
					
			}

	    }
	    
 
	
	 
}