package com.kurukurupapa.tryandroid.apt002;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SimpleEntityDao {
	protected SQLiteDatabase db;

	public SimpleEntityDao(SQLiteDatabase db) {
		this.db = db;
	}

	public void create() {
		db.execSQL("create table simple_entity ("
				+ "id integer primary key autoincrement"
				+ ")");
	}

	public void drop() {
		db.execSQL("drop table if exists simple_entity");
	}

	public void upgrade(int oldVersion, int newVersion) {
		drop();
		create();
	}

	public void execSQL(String sql) {
		db.execSQL(sql);
	}

	public void execSQL(String sql, Object[] bindArgs) {
		db.execSQL(sql, bindArgs);
	}

	public List<com.kurukurupapa.tryandroid.apt002.SimpleEntity> query(
			String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
		List<com.kurukurupapa.tryandroid.apt002.SimpleEntity> result =
			new ArrayList<com.kurukurupapa.tryandroid.apt002.SimpleEntity>();
		Cursor cursor = null;
		try {
			cursor = db.query("simple_entity",
				new String[] {
					"id",
				},
				selection, selectionArgs, groupBy, having, orderBy);
			while (cursor.moveToNext()) {
				result.add(getEntityFromCursor(cursor));
			}
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return result;
	}

	public List<com.kurukurupapa.tryandroid.apt002.SimpleEntity> query() {
		return query(null, null, null, null, "id");
	}

	public long insert(com.kurukurupapa.tryandroid.apt002.SimpleEntity entity) {
		ContentValues values = getContentValuesForInsert(entity);
		long id = db.insert("simple_entity", null, values);
		return id;
	}

	public int update(com.kurukurupapa.tryandroid.apt002.SimpleEntity entity) {
		int count = db.update(
			"simple_entity",
			getContentValuesForUpdate(entity),
			"id=" + entity.getId(),
			null);
		return count;
	}

	public int delete(com.kurukurupapa.tryandroid.apt002.SimpleEntity entity) {
		int count = db.delete(
			"simple_entity",
			"id=" + entity.getId(),
			null);
		return count;
	}

	protected ContentValues getContentValuesForInsert(com.kurukurupapa.tryandroid.apt002.SimpleEntity entiry) {
		ContentValues values = new ContentValues();
		return values;
	}

	protected ContentValues getContentValuesForUpdate(com.kurukurupapa.tryandroid.apt002.SimpleEntity entiry) {
		ContentValues values = getContentValuesForInsert(entiry);
		values.put("id", entiry.getId());
		return values;
	}

	protected com.kurukurupapa.tryandroid.apt002.SimpleEntity getEntityFromCursor(Cursor cursor) {
		com.kurukurupapa.tryandroid.apt002.SimpleEntity entiry = new com.kurukurupapa.tryandroid.apt002.SimpleEntity();
		entiry.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
		return entiry;
	}

}
