package com.example.listviewcustom02;

import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

 private ContactsDbAdapter dbHelper;
 private SimpleCursorAdapter dataAdapter;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  dbHelper = new ContactsDbAdapter(this);
  dbHelper.open();

  //Clean all data
  dbHelper.deleteAllCountries();
  //Add some data
  dbHelper.insertSomeCountries();

  //Generate ListView from SQLite Database
  //displayListView();
  
  String KEY_ROWID = "_id";
	 String KEY_CODE = "code";
	 String KEY_NAME = "name";
	 String KEY_CONTINENT = "continent";
	 String KEY_REGION = "region";

	 Cursor cursor = dbHelper.fetchAllCountries();

	 ArrayList items = new ArrayList(); 

	 for(int i=0;i<cursor.getCount();i++)
	 {
		  String item1 = cursor.getString(cursor.getColumnIndex(KEY_ROWID));
		  String item2 = cursor.getString(cursor.getColumnIndex(KEY_CODE));
		  String item3 = cursor.getString(cursor.getColumnIndex(KEY_NAME));
		  String item4 = cursor.getString(cursor.getColumnIndex(KEY_CONTINENT));
		  String item5 = cursor.getString(cursor.getColumnIndex(KEY_REGION));
		  String firstChar = item3.substring(0, 1);
		  items.add(new ListCell(item1,item2, item3, item4, item5,firstChar));
		  cursor.moveToNext();
	  }
	 
	 items = sortAndAddSections(items);

 }

 
 private ArrayList sortAndAddSections(ArrayList itemList)
 {
     
     ArrayList tempList = new ArrayList();
     //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 displayListView() {

	 String KEY_ROWID = "_id";
	 String KEY_CODE = "code";
	 String KEY_NAME = "name";
	 String KEY_CONTINENT = "continent";
	 String KEY_REGION = "region";

	 Cursor cursor = dbHelper.fetchAllCountries();
  
	 ArrayList items = new ArrayList(); 
  
	 for(int i=0;i<cursor.getCount();i++)
	 {
		  String item1 = cursor.getString(cursor.getColumnIndex(KEY_ROWID));
		  String item2 = cursor.getString(cursor.getColumnIndex(KEY_CODE));
		  String item3 = cursor.getString(cursor.getColumnIndex(KEY_NAME));
		  String item4 = cursor.getString(cursor.getColumnIndex(KEY_CONTINENT));
		  String item5 = cursor.getString(cursor.getColumnIndex(KEY_REGION));
		  String firstChar = item3.substring(0, 1);
		  items.add(new ListCell(item1,item2, item3, item4, item5,firstChar));
		  cursor.moveToNext();
	  }
 
	 

  
  //indexer = new AlphabetIndexer(c, c.getColumnIndexOrThrow(DbHelper.COUNTRIES_NAME), "ABCDEFGHIJKLMNOPQRSTUVWXYZ");

  // The desired columns to be bound
  String[] columns = new String[] {
		  ContactsDbAdapter.KEY_CODE,
		  ContactsDbAdapter.KEY_NAME,
		  ContactsDbAdapter.KEY_CONTINENT,
		  ContactsDbAdapter.KEY_REGION
  };

  // the XML defined views which the data will be bound to
  int[] to = new int[] { 
    R.id.code,
    R.id.name,
    R.id.continent,
    R.id.region,
  };

  // create the adapter using the cursor pointing to the desired data 
  //as well as the layout information
  dataAdapter = new SimpleCursorAdapter(
    this, R.layout.contacts_info, 
    cursor, 
    columns, 
    to,
    0);

  ListView listView = (ListView) findViewById(R.id.listView1);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);


  listView.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> listView, View view, 
     int position, long id) {
   // Get the cursor, positioned to the corresponding row in the result set
   Cursor cursor = (Cursor) listView.getItemAtPosition(position);

   // Get the state's capital from this row in the database.
   String countryCode = 
    cursor.getString(cursor.getColumnIndexOrThrow("code"));
   Toast.makeText(getApplicationContext(),
     countryCode, Toast.LENGTH_SHORT).show();

   }
  });

  EditText myFilter = (EditText) findViewById(R.id.myFilter);
  myFilter.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {
   }

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

   public void onTextChanged(CharSequence s, int start, 
     int before, int count) {
    dataAdapter.getFilter().filter(s.toString());
   }
  });
  
  dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
         public Cursor runQuery(CharSequence constraint) {
             return dbHelper.fetchCountriesByName(constraint.toString());
         }
     });

 }
 
 
 
 
 
 
}

