/*
 *  The MIT License
 *
 *  Copyright 2014 Masahiko, SAWAI <masahiko.sawai@gmail.com>.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
package com.example.hello.android.ui_pattern_listview_crud_db;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import com.example.hello.android.ui_pattern_listview_crud_db.db.UserDBHelper;

public class UserListViewActivity extends ListActivity
	implements OnItemClickListener, UserListConstants
{

	private static final String LOG_TAG = "XXX";
	// instances
	private SimpleCursorAdapter userListAdapter;
	private UserDBHelper dbHelper;
	private SQLiteDatabase db;
	private Cursor cursor;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		Log.v(LOG_TAG, "onCreate() : Hello");

		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_list_view_activity);

		initializeDb();

		// Init ListAdapter
		userListAdapter = new SimpleCursorAdapter(this,
			R.layout.user_list_item, null, MAPPING_FROM, MAPPING_TO);
		setListAdapter(userListAdapter);

		// Init ListView
		ListView listView = getListView();
		listView.setOnItemClickListener(this);
		registerForContextMenu(listView);

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

	@Override
	protected void onDestroy()
	{
		Log.v(LOG_TAG, "onDestroy() : Hello");
		finalizeDb();
		super.onDestroy();
		Log.v(LOG_TAG, "onDestroy() : Bye");
	}

	@Override
	protected void onResume()
	{
		Log.v(LOG_TAG, "onResume() : Hello");
		super.onResume();
		updateListData();
		Log.v(LOG_TAG, "onResume() : Bye");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		Log.v(LOG_TAG, "onActivityResult() : Hello");
		Log.d(LOG_TAG, "onActivityResult() : requestCode => " + requestCode);
		Log.d(LOG_TAG, "onActivityResult() : resultCode => " + resultCode);

		switch (requestCode)
		{
			case REQUEST_CODE_ADD_USER:
				Log.d(LOG_TAG, "onActivityResult() : Add new user is done.");
				if (resultCode == RESULT_OK)
				{
					updateListData();
				}
				break;
			case REQUEST_CODE_EDIT_USER:
				Log.d(LOG_TAG, "onActivityResult() : Edit user is done.");
				if (resultCode == RESULT_OK)
				{
					Log.d(LOG_TAG, "onActivityResult() : RESULT_OK");
					updateListData();
				}
				break;
			case REQUEST_CODE_VIEW_USER:
				Log.d(LOG_TAG, "onActivityResult() : View user is done.");
				if (resultCode == RESULT_OK)
				{
					updateListData();
				}
				break;
			case REQUEST_CODE_DELETE_USER:
				Log.d(LOG_TAG, "onActivityResult() : Delete user is done.");
				if (resultCode == RESULT_OK)
				{
					updateListData();
				}
				break;
		}

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

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		Log.v(LOG_TAG, "onCreateContextMenu() : Hello");
		super.onCreateContextMenu(menu, v, menuInfo);

		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.user_list_context_menu, menu);

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

	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		boolean result;

		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
		Log.v(LOG_TAG, "onCreateContextMenu() : list item position => " + menuInfo.position);
		Log.v(LOG_TAG, "onCreateContextMenu() : list item id => " + menuInfo.id);
		Log.v(LOG_TAG, "onCreateContextMenu() : list item targetView => " + menuInfo.targetView);

		int itemId = item.getItemId();
		switch (itemId)
		{
			case R.id.edit_menuitem:
				editUserById(menuInfo.id);
				result = true;
				break;
			case R.id.delete_menuitem:
				deleteUserById(menuInfo.id);
				result = true;
				break;
			default:
				result = super.onContextItemSelected(item);
		}

		return result;
	}

	public void onItemClick(AdapterView<?> parentView, View view, int position, long id)
	{
		Log.v(LOG_TAG, "onItemClick() : Hello");
		Log.d(LOG_TAG, "onItemClick() : position => " + position + ", id => " + id);

		viewUserDetailById(id);

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.user_list_option_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Log.v(LOG_TAG, "onOptionsItemSelected() : Hello");
		boolean result = true;

		int itemId = item.getItemId();
		switch (itemId)
		{
			case R.id.add_menuitem:
				Log.d(LOG_TAG, "onOptionsItemSelected() : Add menu item selected.");
				addNewUser();
				break;
			case R.id.delete_menuitem:
				Log.d(LOG_TAG, "onOptionsItemSelected() : Delete menu item selected.");
				deleteUsers();
				break;
			default:
				result = super.onOptionsItemSelected(item);
		}

		Log.v(LOG_TAG, "onOptionsItemSelected() : Bye");
		return result;
	}

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

		db = dbHelper.getReadableDatabase();

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

	private void finalizeDb()
	{
		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 swapCursor(Cursor newCursor)
	{
		userListAdapter.changeCursor(newCursor);
		if (cursor != null)
		{
			cursor.close();
		}
		cursor = newCursor;
	}

	private void updateListData()
	{
		Log.v(LOG_TAG, "updateListData() Hello");

		if (db != null)
		{
			Log.d(LOG_TAG, "updateListData() : change new cursor!");
			Cursor newCursor = dbHelper.getAllUsers(db);
			swapCursor(newCursor);
		}

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

	private void addNewUser()
	{
		Intent intent = new Intent(this, UserDetailEditActivity.class);
		intent.setAction(Intent.ACTION_EDIT);
		startActivityForResult(intent, REQUEST_CODE_ADD_USER);
	}

	private void viewUserDetailById(long id)
	{
		Intent intent = new Intent(this, UserDetailViewActivity.class);
		intent.setAction(Intent.ACTION_VIEW);
		intent.putExtra(UserDetailViewActivity.EXTRA_ID, id);
		startActivityForResult(intent, REQUEST_CODE_VIEW_USER);
	}

	private void editUserById(long id)
	{
		Intent intent = new Intent(this, UserDetailEditActivity.class);
		intent.setAction(Intent.ACTION_EDIT);
		intent.putExtra(UserDetailEditActivity.EXTRA_ID, id);
		startActivityForResult(intent, REQUEST_CODE_EDIT_USER);
	}

	private void deleteUserById(long id)
	{
		int count = dbHelper.deleteUserById(db, id);
		if (count > 0)
		{
			updateListData();
		}
	}

	private void deleteUsers()
	{
		Intent intent = new Intent(this, UserListDeleteActivity.class);
		startActivityForResult(intent, REQUEST_CODE_DELETE_USER);
	}
}
