package org.azavea.otm.ui;


import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

import org.azavea.otm.App;
import org.azavea.otm.R;
import org.azavea.otm.FilterManager;
import org.azavea.otm.adapters.SpeciesAdapter;
import org.azavea.otm.data.Species;
import org.json.JSONException;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class SpeciesListDisplay extends ListActivity {
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		FilterManager search = App.getFilterManager();
		
		if (search.getSpecies().size() > 0) {
			renderSpeciesList();
		} else {
			search.loadSpeciesList(new Callback() {

				@Override
				public boolean handleMessage(Message msg) {
					if (msg.getData().getBoolean("success")) {
						renderSpeciesList();
					} else {
						Toast.makeText(App.getInstance(), "Could not get species list", 
								Toast.LENGTH_SHORT).show();
					}
					return true;
				}
				
			});
		}
	}
	
	private void renderSpeciesList() {
		LinkedHashMap<Integer, Species> list = App.getFilterManager().getSpecies();
		Species[] species = new Species[list.size()];
		int i = 0;
		for (Map.Entry<Integer,Species> entry : list.entrySet()) {
			species[i] = entry.getValue();
			i++;
		}
		// Sort by common name
		Arrays.sort(species);
		
		// Bind the custom adapter to the view
		SpeciesAdapter adapter = new SpeciesAdapter(this, R.layout.species_list_row, 
				species);
		Log.d(App.LOG_TAG, list.size() + " species loaded");
		setListAdapter(adapter);
		setContentView(R.layout.species_list_selector);
		setupFiltering(adapter);
	}
	
	private void setupFiltering(final SpeciesAdapter adapter) {
		EditText filterEditText = (EditText) findViewById(R.id.species_filter_text);
		filterEditText.addTextChangedListener(new TextWatcher() {
		   @Override
		    public void onTextChanged(CharSequence s, int start, int before,
		    		int count) {
			   //adapter.getFilter().filter(s.toString());
		    }

			@Override
			public void afterTextChanged(Editable s) {
				adapter.getFilter().filter(s);
				adapter.notifyDataSetChanged();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			}); 		
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Species selection = (Species)l.getItemAtPosition(position);
		Intent result = new Intent();
		// The underlying JSONObject of Species is not serializable, so just 
		// return the information to use for querying
		try {
			result.putExtra("species_id", selection.getId());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		setResult(RESULT_OK, result);
		finish();
	}	    
  }

@@ -547,16 +547,46 @@
 il.Log;%0A
+import android.view.KeyEvent;%0A
 import a
@@ -599,24 +599,24 @@
 .view.View;%0A
-
 import andro
@@ -1132,24 +1132,32 @@
 %0A%09%09%09%09%09%7D else
+%0A%09%09%09%09%09%09 
  %7B%0A%09%09%09%09%09%09Toa
@@ -1289,13 +1289,8 @@
 %09%09%7D%0A
-%09%09%09%09%0A
 %09%09%09%7D
@@ -1929,16 +1929,17 @@
 apter);%0A
+%0A
 %09%7D%0A%09%0A%09pr
@@ -2071,24 +2071,343 @@
 lter_text);%0A
+%09%09setKeyboardChangeEvents(adapter, filterEditText);%0A%09%09setTextWatcherEvents(adapter, filterEditText); %09%09%0A%09%7D%0A%0A%09/**%0A%09 * Listen on events of the filter text box to pass along filter text%0A%09 * and invalidate the current view%0A%09 */%0A%09private void setTextWatcherEvents(final SpeciesAdapter adapter,%0A%09%09%09EditText filterEditText) %7B%0A
 %09%09filterEdit
@@ -2564,65 +2564,8 @@
 t) %7B
-%0A%09%09%09   //adapter.getFilter().filter(s.toString());%0A%09%09    
 %7D%0A%0A%09
@@ -2808,19 +2808,688 @@
 %7D%0A%09%09%09%7D);
- %09%09
+%0A%09%7D%0A%0A%09/**%0A%09 *  Listen on events the keyboard emits when finished editing%0A%09 *  ('Done' and 'Next' are the ENTER event).%0A%09 *  The Keyboard ENTER event on a ListActivity will re-render%0A%09 *  the list, so the current view must be invalidated%0A%09 */%0A%09private void setKeyboardChangeEvents(final SpeciesAdapter adapter,%0A%09%09%09EditText filterEditText) %7B%0A%09%09filterEditText.setOnKeyListener(new View.OnKeyListener()%0A%09    %7B%0A%09        public boolean onKey(View v, int keyCode, KeyEvent event)%0A%09        %7B%0A%09            if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)%0A%09            %7B%0A%09                adapter.notifyDataSetChanged();%0A%09            %7D%0A%09            return false;%0A%09        %7D%0A%09    %7D);
 %0A%09%7D%0A%09%0A%09@
@@ -3959,12 +3959,11 @@
 %09%7D%09    %0A
- 
  %7D%0A

Set text and keyboard events on species filter