package com.example.hello.android.searchview_in_actionbar_collapse;

import android.app.ListActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;

public class MainActivity extends ListActivity
	implements SearchView.OnQueryTextListener,
	View.OnClickListener
{

	private static final String LOG_TAG = "XXX";
	private ListView listView;

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.main_activity_option_menu, menu);

		// SearchView の取得
		MenuItem searchMenuItem = menu.findItem(R.id.search_menuitem);
		SearchView searchView = (SearchView) searchMenuItem.getActionView();
//		searchView.setIconifiedByDefault(true);
		searchView.setSubmitButtonEnabled(false);
		searchView.setOnSearchClickListener(this);
		searchView.setOnQueryTextListener(this);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		boolean result = true;

		switch (item.getItemId())
		{
			case R.id.quit_menuitem:
				finish();
				break;
			default:
				result = super.onOptionsItemSelected(item);
		}

		return result;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		Log.v(LOG_TAG, "Hello");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);

		listView = getListView();
		listView.setTextFilterEnabled(true);

		Log.v(LOG_TAG, "Bye");
	}

	@Override
	public boolean onQueryTextSubmit(String query)
	{
		Log.v(LOG_TAG, "onQueryTextSubmit() : Hello");
		Log.v(LOG_TAG, "onQueryTextSubmit() : Bye");
		return false;
	}

	@Override
	public boolean onQueryTextChange(String query)
	{
		Log.v(LOG_TAG, "onQueryTextChange() : Hello");
		Log.v(LOG_TAG, "onQueryTextChange() : query => " + query);
		setQueryText(query);
		Log.v(LOG_TAG, "onQueryTextChange() : Bye");
		return true;
	}

	@Override
	public void onClick(View view)
	{
		Log.v(LOG_TAG, "onClick() : Hello");
		Log.v(LOG_TAG, "onClick() : view => " + view);
		Log.v(LOG_TAG, "onClick() : Bye");
	}

	private void setQueryText(String query)
	{
		if (TextUtils.isEmpty(query))
		{
			listView.clearTextFilter();
		}
		else
		{
			listView.setFilterText(query);
		}
	}
}
