package com.example.listviewcustom03;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;

import android.text.TextWatcher;

import android.widget.TextView.OnEditorActionListener;

public class MainActivity extends Activity 
{
//	private ContactsDbAdapter dbHelper;
//	private SimpleCursorAdapter dataAdapter;
	ArrayList<ListCell> items = new ArrayList<ListCell>();
	
	private ContactHandler handler;
	private List<Contact> contacts;
	EditText editsearch;

	ArrayList<String> listview_names = new ArrayList<String>();
	ArrayList<Integer> array_sort = new ArrayList<Integer>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ActionBar actionBar = getActionBar();
	    actionBar.show();
	    
	    handler = new ContactHandler(getApplicationContext());
		
		
		String KEY_ID = "id";
		String KEY_NOM = "nom";
		String KEY_PRENOM = "prenom";
		String KEY_ADRESSE = "adresse";
		String KEY_EMAIL = "email";
		String KEY_PORTABLE = "portable";
		String KEY_FIXE = "fixe";
		 

/*		
		Button btn_add_new = (Button) findViewById(R.id.btn_add_contact);
		btn_add_new.setOnClickListener(new OnClickListener() 
		{
			
			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(MainActivity.this, NewContact.class);
				startActivity(intent);
			}
		});	
*/
		
		loadContactData();
		
		//ArrayList items = new ArrayList(); 
		//ArrayList<ListCell> items = new ArrayList<ListCell>();
		
//		for(int i=0;i<cursor.getCount();i++)
//		{
//			  int item1 = cursor.getInt(cursor.getColumnIndex(KEY_ID));
//			  String item2 = cursor.getString(cursor.getColumnIndex(KEY_NOM));
//			  String item3 = cursor.getString(cursor.getColumnIndex(KEY_PRENOM));
//			  String item4 = cursor.getString(cursor.getColumnIndex(KEY_ADRESSE));
//			  String item5 = cursor.getString(cursor.getColumnIndex(KEY_EMAIL));
//			  String item6 = cursor.getString(cursor.getColumnIndex(KEY_PORTABLE));
//			  String item7 = cursor.getString(cursor.getColumnIndex(KEY_FIXE));
			  // pour l'ordre alphabétique on prend la premiére lettre du nom -> section headers doit être amélioré  
//			  String firstChar = item2.substring(0, 1);
//			  items.add(new ListCell(item1, item2, item3, item4, item5, item6, item7 , firstChar));
//			  cursor.moveToNext();
//		}

		ListView list = (ListView) findViewById(R.id.list_contacts);
		
//		items = sortAndAddSections(items);
		
		ListAdapter adapter = new ListAdapter(this, items);
		list.setAdapter(adapter);
		
		
		editsearch = (EditText) findViewById(R.id.search);
		/*editsearch.addTextChangedListener(new TextWatcher()
		{
			public void afterTextChanged(Editable s)
			{
                  // Abstract Method of TextWatcher Interface.
			}
			public void beforeTextChanged(CharSequence s,
					int start, int count, int after)
			{
				// Abstract Method of TextWatcher Interface.
			}
			public void onTextChanged(CharSequence s,	int start, int before, int count)
			{
				int textlength = editsearch.getText().length();
			}	
		});*/
		
		
		list.setOnItemClickListener(new OnItemClickListener() 
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,	long id)
			{
				
				Intent intent = new Intent(MainActivity.this, ContactsDetails.class);
				
				int zorro = items.get(position).getId();
				
				intent.putExtra("id", items.get(position).getId());
				intent.putExtra("nom", items.get(position).getNom());
				intent.putExtra("prenom", items.get(position).getPrenom());
				intent.putExtra("adresse", items.get(position).getAdresse());
				intent.putExtra("email", items.get(position).getEmail());
				intent.putExtra("portable", items.get(position).getPortable());
				intent.putExtra("fixe", items.get(position).getFixe());
				startActivity(intent);
				//Toast.makeText(getApplicationContext(), "TRACE", Toast.LENGTH_SHORT).show();
			}
		});
		
		
		
		 
		editsearch.addTextChangedListener(new TextWatcher()
		{
			@Override
            public void onTextChanged(CharSequence s, int start, int before, int count) 
			{
			
				int textlength = editsearch.getText().length();
				//array_sort.clear();
				for (int i = 0; i < listview_names.size(); i++)
				{
					if (textlength <= listview_names.get(i).length())
					{
						if(listview_names.get(i).toLowerCase().contains(editsearch.getText().toString().toLowerCase().trim()))
						{
							// stocke la position dans la liste
							//array_sort.add(listview_names.get(i+1));
							array_sort.add(i);

						}
                    }
				}
				
				contacts = handler.readAllContacts();
				
				items.clear();
				listview_names.clear();
				
				int nb = array_sort.size();
				for(int i=0;i < nb ;i++)
				{	 int index = array_sort.get(i);
					 int item1 =  contacts.get(index).getID();
					 String item2 = contacts.get(index).getNom();
					 String item3 = contacts.get(index).getPrenom();
					 String item4 = contacts.get(index).getAdresse();
					 String item5 = contacts.get(index).getEmail();
					 String item6 = contacts.get(index).getPortable();
					 String item7 = contacts.get(index).getFixe();			
					 items.add(new ListCell(item1, item2, item3, item4, item5, item6, item7 , "firstChar"));
					 listview_names.add(item2);
					 toto(items);
					 
				}
				
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) 
            {

            }

            @Override
            public void afterTextChanged(Editable s) 
            {
                /*if (0 != editsearch.getText().length()) 
                {
                    String spnId = editsearch.getText().toString();
                    Toast.makeText(getApplicationContext(), "TRACE ...", Toast.LENGTH_SHORT).show();
                    
                } else 
                {
                	Toast.makeText(getApplicationContext(), "Filter ...", Toast.LENGTH_SHORT).show();
                }*/
            }
		});
		
		
		
		
	}
	
	public void toto(ArrayList<ListCell> aaa)
	{
		//setListAdapter(new bsAdapter(this));
		//String msg = "";
		ListAdapter adapteraaa = new ListAdapter(this, aaa);
		ListView list = null;
		list.setAdapter(adapteraaa);
		//setListAdapter(new bsAdapter(this));
	}
	
	
	private void setListAdapter(bsAdapter bsAdapter) {
		// TODO Auto-generated method stub
		
	}


	public class bsAdapter extends BaseAdapter
    {
        Activity cntx;
        public bsAdapter(Activity context)
        {
            // TODO Auto-generated constructor stub
            this.cntx=context;

        }

        public int getCount()
        {
            // TODO Auto-generated method stub
            return array_sort.size();
        }

        public Object getItem(int position)
        {
            // TODO Auto-generated method stub
            return array_sort.get(position);
        }

        public long getItemId(int position)
        {
            // TODO Auto-generated method stub
            return array_sort.size();
        }

        public View getView(final int position, View convertView, ViewGroup parent)
        {
            View row=null;
            
            LayoutInflater inflater=cntx.getLayoutInflater();
            row=inflater.inflate(R.layout.search_list_item, null);
            
            TextView   tv	=	(TextView)	row.findViewById(R.id.title);
            
            tv.setText(array_sort.get(position));
            
        return row;
        }
    }
	
	
	private ArrayList<ListCell> sortAndAddSections(ArrayList<ListCell> itemList)
	{
		
		ArrayList<ListCell> tempList = new ArrayList<ListCell>();
		//First we sort the array
		//Collections.sort(itemList);
		
		//Loops thorugh the list and add a section before each sectioncell start
		String header = "";
		for(int i = 0; i < itemList.size(); i++)
		{
			//If it is the start of a new section we create a new listcell and add it to our array
			//if(header != itemList.get(i).getCategory()){
			//	ListCell sectionCell = new ListCell(itemList.get(i).getCategory(), null);
			//	sectionCell.setToSectionHeader();
			//	tempList.add(sectionCell);
			//	header = itemList.get(i).getCategory();
			//}
			tempList.add(itemList.get(i));
		}
		
		return tempList;
	}
	
	
	
	private void loadContactData()
	{
		contacts = handler.readAllContacts();
		
		int nb = contacts.size();
		for(int i=0;i < nb ;i++)
		{
			 int item1 =  contacts.get(i).getID();
			 String item2 = contacts.get(i).getNom();
			 String item3 = contacts.get(i).getPrenom();
			 String item4 = contacts.get(i).getAdresse();
			 String item5 = contacts.get(i).getEmail();
			 String item6 = contacts.get(i).getPortable();
			 String item7 = contacts.get(i).getFixe();			
			 items.add(new ListCell(item1, item2, item3, item4, item5, item6, item7 , "firstChar"));
			 listview_names.add(item2);
		}
/*		
		// Initialize Custom Adapter 
		CustomAdapter adapter = new CustomAdapter(this, contacts);
		
		// Set Adapter to ListView
		lv.setAdapter(adapter);		
		
		// See the log int LogCat
		for(Contact c : contacts)
		{
			String record = "ID=" + c.getID() + " | Name=" + c.getName() + " | " + c.getPhoneNumber();			
			Log.d("Record",record);
		}
*/		
	}	

	
	
	
	@Override
	 public boolean onCreateOptionsMenu(Menu menu) 
	 {
	      getMenuInflater().inflate(R.menu.main, menu);
	      return true;
	 }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    switch (item.getItemId())
	    {
		    case R.id.menu_about:
		        // Comportement du bouton "A Propos"
		        return true;
		    case R.id.menu_help:
		        // Comportement du bouton "Aide"
		        return true;
		    case R.id.menu_refresh:
		        // Comportement du bouton "Rafraichir"
		        return true;
		    case R.id.menu_search:
		        // Comportement du bouton "Recherche"
		        return true;
		    case R.id.menu_settings:
		        // Comportement du bouton "Paramètres"
	    		Toast.makeText(getBaseContext(), "Infos", Toast.LENGTH_SHORT).show();
	    		Intent intent5 = new Intent(this, InfosApplication.class);
	            startActivity(intent5); 
		    default:
		        return super.onOptionsItemSelected(item);
	    }
	}
}
