/*
 *  The MIT License
 *
 *  Copyright 2011 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.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.hello.android.ui_pattern_listview_crud_db.R;
import java.util.Random;

public class UserDBHelper extends SQLiteOpenHelper implements UserDBConstants
{

	private static final String LOG_TAG = "XXX";
	static final int DB_VERSION = 1;
	static final String DB_NAME = "Users";
	private Context context;

	public UserDBHelper(Context context)
	{
		// create database on main memory
		super(context, DB_NAME, null, DB_VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL(CREATE_TABLE_SQL);
		initializeUsers(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		db.execSQL(DROP_TABLE_SQL);
		onCreate(db);
	}

	public Cursor selectUsersById(SQLiteDatabase db, long id)
	{
		Cursor cursor = db.query(TABLE_NAME,
			new String[]
		{
			Columns.ID,
			Columns.FIRST_NAME,
			Columns.LAST_NAME,
			Columns.EMAIL,
			Columns.AGE,
		},
			Columns.ID + " = ?",
			new String[]
		{
			String.valueOf(id)
		},
			null, null, null);

		return cursor;
	}

	public Cursor selectUsersByName(SQLiteDatabase db, String firstName)
	{
		Cursor cursor = db.query(TABLE_NAME,
			new String[]
		{
			Columns.ID,
			Columns.FIRST_NAME,
			Columns.LAST_NAME,
			Columns.EMAIL,
			Columns.AGE,
		},
			Columns.FIRST_NAME + " like ?",
			new String[]
		{
			'%' + firstName + '%'
		},
			null, null, Columns.FIRST_NAME + " ASC");

		return cursor;
	}

	public Cursor getAllUsers(SQLiteDatabase db)
	{
		Cursor cursor = db.query(TABLE_NAME,
			new String[]
		{
			Columns.ID,
			Columns.FIRST_NAME,
			Columns.LAST_NAME,
			Columns.FIRST_NAME,
			Columns.EMAIL,
			Columns.AGE,
		},
			null, null,
			null, null, Columns.FIRST_NAME + " ASC");

		return cursor;
	}

	public void insertUser(SQLiteDatabase db,
		String firstName, String lastName,
		String email, int age)
	{
		ContentValues values = new ContentValues();
		values.clear();
		values.put(Columns.FIRST_NAME, firstName);
		values.put(Columns.LAST_NAME, lastName);
		values.put(Columns.EMAIL, email);
		values.put(Columns.AGE, age);
		db.insert(TABLE_NAME, null, values);
	}

	public void updateUserById(SQLiteDatabase db, long id,
		String firstName, String lastName,
		String email, int age)
	{
		ContentValues values = new ContentValues();
		values.clear();
		values.put(Columns.FIRST_NAME, firstName);
		values.put(Columns.LAST_NAME, lastName);
		values.put(Columns.EMAIL, email);
		values.put(Columns.AGE, age);
		db.update(TABLE_NAME, values,
			Columns.ID + " = ? ",
			new String[]
		{
			String.valueOf(id)
		});
	}

	public int deleteUserById(SQLiteDatabase db, long id)
	{
		int deletedCount = db.delete(TABLE_NAME,
			Columns.ID + " = ? ",
			new String[]
		{
			String.valueOf(id)
		});
		return deletedCount;
	}

	private void initializeUsers(SQLiteDatabase db)
	{
		Log.d(LOG_TAG, "initializeUsers() Hello");

		ContentValues values = new ContentValues();
		db.beginTransaction();
		try
		{
			String[] names = this.context.getResources().getStringArray(R.array.names);
			Random rand = new Random(0);
			for (String firstName : names)
			{
				try
				{
					int age = 15 + rand.nextInt(10); // 15 - 24
					values.clear();
					values.put(Columns.FIRST_NAME, firstName);
					values.put(Columns.LAST_NAME, "Smith");
					values.put(Columns.EMAIL, firstName.toLowerCase() + "@example.com");
					values.put(Columns.AGE, age);

					db.insert(TABLE_NAME, null, values);
				}
				catch (IllegalArgumentException ex)
				{
					Log.e(LOG_TAG, "insert data failed.", ex);
				}
			}
			db.setTransactionSuccessful();
		}
		finally
		{
			db.endTransaction();
		}

		Log.d(LOG_TAG, "initializeUsers() Bye");
	}
}
