/*
 *  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.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import com.example.hello.android.ui_pattern_listview_crud_db.db.UserDBHelper;

public class UserListDeleteActivity extends ListActivity
	implements View.OnClickListener, UserListConstants
{

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

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

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

		initializeDb();

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

		// Init ListView
		ListView listView = getListView();
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		// Init listeners
		Button cancelButton = (Button) findViewById(R.id.cancel_button);
		cancelButton.setOnClickListener(this);

		Button deleteButton = (Button) findViewById(R.id.delete_button);
		deleteButton.setOnClickListener(this);

		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");
		updateListData();
		super.onResume();
		Log.v(LOG_TAG, "onResume() : Bye");
	}

	public void onClick(View view)
	{
		Log.v(LOG_TAG, "onClick() : Hello");

		int viewId = view.getId();
		switch (viewId)
		{
			case R.id.cancel_button:
				Log.d(LOG_TAG, "Cancel Button is clicked.");
				setResult(RESULT_CANCELED);
				finish();
				break;
			case R.id.delete_button:
				Log.d(LOG_TAG, "Delete Button is clicked.");
				deleteCheckedUsers();
				setResult(RESULT_OK);
				finish();
				break;
		}

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

	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 deleteCheckedUsers()
	{
		Log.v(LOG_TAG, "deleteSelectedUsers() : Hello");

		ListView listView = getListView();
		SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();

		for (int i = 0; i < checkedItemPositions.size(); i++)
		{
			if (checkedItemPositions.valueAt(i))
			{
				int position = checkedItemPositions.keyAt(i);
				long id = listView.getItemIdAtPosition(position);
				dbHelper.deleteUserById(db, id);
			}
		}

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