var RecordDB = function() {
	this.dbName = 'recorddb';

	this.open = function () {
		this.db = Titanium.Database.open(this.dbName);
	};
	this.close = function () {
		this.db.close();
	};
	this.setRows = function (rows) {
		var res = [];
		if ( rows.getRowCount() > 0 ) {
			Ti.API.debug('Found: ' + rows.getRowCount() );
			for (i =0; rows.isValidRow(); i++) {
				var record = {};
				record.id = rows.fieldByName('id');
				record.weight = rows.fieldByName('weight');
				var time = rows.fieldByName('at', Titanium.Database.FIELD_TYPE_DOUBLE)
				var at = new Date();
				at.setTime(time);
				record.at = at.toDateString();
				res.push(record);
				rows.next();
			}
		}
		return res;
	};
	this.deleteOne = function(record) {
		this.open();
		var res = this.db.execute(
		'DELETE FROM records WHERE id=?',
		record.id
		);
		Ti.API.debug('Delete from DB');
		this.close();
		return true;
	};
	this.update = function(record) {
		this.open();
		var at = new Date(record.at);
		var res = this.db.execute(
		'UPDATE records SET weight=?, at=? WHERE id=?',
		record.weight,
		at.getTime(),
		record.id
		);
		Ti.API.debug('Update DB');
		this.close();
		return true;
	};
	this.findAll = function() {
		this.open();
		var rows = this.db.execute( 'SELECT * FROM records ORDER BY at DESC' );
		var res = this.setRows(rows);
		rows.close();
		this.close();
		return res;
	};
	this.insert = function(record) {
		this.open();
		var at = new Date(record.at);
		var res = this.db.execute(
		'INSERT INTO records (weight, at) VALUES(?,?)',
		record.weight,
		at.getTime()
		);
		Ti.API.debug('Insert into DB');
		this.close();
	};
	this.findById = function(id) {
		this.open();
		var rows = this.db.execute( 'SELECT * FROM records WHERE id=?', id );
		var res = this.setRows(rows);
		rows.close();
		this.close();
		if (res.length > 0)
			return res[0];
		else
			return null;
	};
	this.deleteAll = function() {
		Ti.API.debug("deleteAll");
		this.open();
		var rows = this.db.execute( 'DELETE FROM records' );
		this.close();
		return true;
	};
	this.restore = function(records) {
		Ti.API.debug("restore");
		this.deleteAll();
		var last = records.length-1;
		for (i = last; i >= 0; i--)
			this.insert(records[i]);
	}
	// テーブル作成
	this.open();
	//this.db.execute('DROP TABLE records');
	this.db.execute('CREATE TABLE IF NOT EXISTS records ( id INTEGER PRIMARY KEY, weight TEXT, at REAL)');
	this.close();
};