package com.kurukurupapa.tryandroiddb.db001;

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

import com.kurukurupapa.tryandroid.fw.util.LogUtil;

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

/**
 * サンプルテーブル操作クラス
 */
public class RecordDao {
	private SQLiteDatabase db;

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

	public List<Record> findAll() {
		List<Record> result = new ArrayList<Record>();
		Cursor cursor = db.query("record",
				new String[] { "id", "text", "timestamp" }, null, null, null, null,
				"id");
		while (cursor.moveToNext()) {
			Record record = new Record();
			record.id = cursor.getInt(0);
			record.text = cursor.getString(1);
			record.setTimestamp(cursor.getLong(2));
			result.add(record);
		}
		cursor.close();
		LogUtil.d("count=" + result.size());
		return result;
	}

	public long insert(Record record) {
		record.timestamp = System.currentTimeMillis();
		ContentValues values = record.getNoIdContentValues();
		long count = db.insert("record", null, values);
		LogUtil.d("id=" + values.getAsInteger("id") + ", count=" + count);
		return count;
	}

	public int update(Record record) {
		int count = db.update("record", record.getFullContentValues(), "id="
				+ record.id, null);
		LogUtil.d("id=" + record.id + ", count=" + count);
		return count;
	}

	public int delete(Record record) {
		int count = db.delete("record", "id=" + record.id, null);
		LogUtil.d("id=" + record.id + ", count=" + count);
		return count;
	}
}
