package com.example.hello.android.searchview_recent_query_suggestion.db;

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

/**
 *
 * @author sawai
 */
public class UserListOpenHelper extends SQLiteOpenHelper
{

	private static final String LOG_TAG = "XXX";
	static final String DB_NAME = "userlist.sqlite";
	static final int DB_VERSION = 1;
	static final String TABLE_NAME = "Users";
	static final String CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + "("
		+ "  _id INTEGER PRIMARY KEY AUTOINCREMENT"
		+ ", name TEXT"
		+ ", age INTEGER"
		+ ", email TEXT"
		+ ");";
	static final String DROP_TABLE_SQL = "DROP TABLE " + TABLE_NAME + ";";
	private Context context;

	public UserListOpenHelper(Context context)
	{
		super(context, DB_NAME, null, DB_VERSION);
		this.context = context;
	}

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

		insertUsers(db);
	}

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

	private void insertUsers(SQLiteDatabase db)
	{
		String[] names = context.getResources().getStringArray(R.array.names);
		ContentValues values = new ContentValues();

		Random rand = new Random(0);
		for (String name : names)
		{
			int age = rand.nextInt(10) - 5 + 20;
			values.clear();
			values.put("name", name);
			values.put("age", age);
			values.put("email", name + "@example.com");
			db.insert(TABLE_NAME, null, values);
		}
	}

	public Cursor selectByName(SQLiteDatabase db, String nameQuery)
	{
		Cursor cursor;

		String name = (nameQuery == null) ? "" : nameQuery.trim();
		if (name.length() > 0)
		{
			cursor = db.query(TABLE_NAME, null,
				"name like ?", new String[]
				{
					"%" + name + "%"
				},
				null, null, "name ASC");
			Log.d(LOG_TAG, "cursor => " + cursor);
		}
		else
		{
			cursor = db.query(TABLE_NAME, null,
				null, null, null, null, "name ASC");
			Log.d(LOG_TAG, "cursor => " + cursor);
		}
		return cursor;
	}
}
