package com.example.hello.android.searchview_recent_query_suggestion;

import android.app.ListActivity;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import com.example.hello.android.searchview_recent_query_suggestion.db.UserListOpenHelper;
import com.example.hello.android.searchview_recent_query_suggestion.db.UserSearchRecentSuggestionProvider;
import com.example.hello.android.searchview_recent_query_suggestion.util.Log;

public class UserListActivity extends ListActivity
	implements SearchView.OnCloseListener
{

	private static final String LOG_TAG = "XXX";
	private static final String[] MAPPING_FROM = new String[]
	{
		"name", "email"
	};
	private static final int[] MAPPING_TO = new int[]
	{
		android.R.id.text1, android.R.id.text2,
	};
	private UserListOpenHelper dbHelper;
	private SQLiteDatabase db;
	private Cursor cursor;
	private SimpleCursorAdapter adapter;
	private SearchView searchView;

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

		// SearchView の取得
		MenuItem searchMenuItem = menu.findItem(R.id.search_menuitem);
		searchView = (SearchView) searchMenuItem.getActionView();
		searchView.setOnCloseListener(this);

		// このアクティビティの SearchableInfo を取得
		// (AndroidManifest.xml で設定してある SearchableInfo が取得される)
		SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
		SearchableInfo searchableInfo = searchManager.getSearchableInfo(getComponentName());

		// SearchView に SearchableInfo を設定
		searchView.setSearchableInfo(searchableInfo);

		// SearchView の表示の設定
		searchView.setIconifiedByDefault(true);
		searchView.setSubmitButtonEnabled(false);

		return true;
	}

	@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;
	}

	public boolean onClose()
	{
		Log.v(LOG_TAG, "Hello");
		updateListData(null);
		Log.v(LOG_TAG, "Bye");

		return false;
	}

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

		initializeListData();

		Intent queryIntent = getIntent();
		String queryAction = queryIntent.getAction();
		Log.v(LOG_TAG, "queryAction => " + queryAction);

		if (Intent.ACTION_SEARCH.equals(queryAction))
		{
			Log.v(LOG_TAG, "action => ACTION_SEARCH");
			doSearchWithIntent(queryIntent);
		}
		else if (Intent.ACTION_VIEW.equals(queryAction))
		{
			Log.v(LOG_TAG, "intent.action => ACTION_VIEW");
			Log.v(LOG_TAG, "intent.data => " + queryIntent.getData());
			Log.v(LOG_TAG, "intent.type => " + queryIntent.getType());
			Log.v(LOG_TAG, "intent.scheme => " + queryIntent.getScheme());

			int flags = queryIntent.getFlags();
			Log.v(LOG_TAG, "flags => 0x" + Integer.toHexString(flags));

			if ((queryIntent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) != 0)
			{
				Log.v(LOG_TAG, "flags includes FLAG_ACTIVITY_NEW_TASK");
				doSearchWithIntent(queryIntent);
			}
		}

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

	@Override
	protected void onNewIntent(Intent intent)
	{
		Log.v(LOG_TAG, "Hello");

		Log.d(LOG_TAG, "intent => " + intent.getAction());
		doSearchWithIntent(intent);

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

	@Override
	protected void onDestroy()
	{
		Log.v(LOG_TAG, "Hello");

		finalizeListData();

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

	private void doSearchWithIntent(Intent queryIntent)
	{
		Log.v(LOG_TAG, "Hello");

		String queryString = queryIntent.getStringExtra(SearchManager.QUERY);
		doSearchWithQuery(queryString);

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

	private void doSearchWithQuery(String queryString)
	{
		Log.d(LOG_TAG, "queryString => " + queryString);

		// update
		updateListData(queryString);

		// save query
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
			UserSearchRecentSuggestionProvider.AUTHORITY,
			UserSearchRecentSuggestionProvider.DATABASE_MODE_QUERIES);
		suggestions.saveRecentQuery(queryString, null);
	}

	private void initializeListData()
	{
		Log.v(LOG_TAG, "Hello");
		if (dbHelper == null)
		{
			dbHelper = new UserListOpenHelper(this);
		}

		db = dbHelper.getReadableDatabase();

		cursor = dbHelper.selectByName(db, null);

		adapter = new SimpleCursorAdapter(this,
			android.R.layout.simple_list_item_2, cursor, MAPPING_FROM, MAPPING_TO);
		setListAdapter(adapter);
		Log.v(LOG_TAG, "Bye");
	}

	private void finalizeListData()
	{
		Log.v(LOG_TAG, "Hello");
		if (cursor != null)
		{
			cursor.close();
			cursor = null;
		}
		if (db != null)
		{
			db.close();
			db = null;
		}
		Log.v(LOG_TAG, "Bye");
	}

	private void updateListData(String queryString)
	{
		Log.v(LOG_TAG, "Hello");
		if (db != null)
		{
			Cursor newCursor = dbHelper.selectByName(db, queryString);
			adapter.changeCursor(newCursor);
			if (cursor != null)
			{
				cursor.close();
			}
			cursor = newCursor;
		}
		Log.v(LOG_TAG, "Bye");
	}
}
