package database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
	public static final String KEY_ID="_id";
	public static final String NAME="name";
	public static final String ADDRESS="addr";
	public static final String TEL="tel";
	public static final String DB_CREATE=
	"create table titles (_id integer primary key autoincrement," +
	"name text not null, addr text not null, " +
	"tel text not null);";
	
	private static final String DATABASE_NAME="Interactors";
	private static final String DATABASE_TABLE="titles";
	private static final String TAG="DBAdapter";
	
	private final Context context;
	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;
	public DBAdapter(Context ctx)
	{
		this.context=ctx;
		DBHelper=new DatabaseHelper(context);
	}
	
	private static class DatabaseHelper extends SQLiteOpenHelper
	{
		DatabaseHelper(Context context)
		{
			super(context,DATABASE_NAME,null,1);
		}
		
		public void onCreate(SQLiteDatabase db)
		{
			db.execSQL(DB_CREATE);
		}
		
		public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
		{
			Log.w(TAG, "Upgrading database from version "+oldVersion
					+" to "+newVersion+", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS titles");
			onCreate(db);
		}
	}
	
	public DBAdapter open() throws SQLException
	{
		db=DBHelper.getWritableDatabase();
		return this;
	}
	
	public void close()
	{
		DBHelper.close();
	}
	
	public long insertTitle(String name,String addr,String tel)
	{
		ContentValues ini=new ContentValues();
		ini.put(NAME, name);
		ini.put(ADDRESS, addr);
		ini.put(TEL, tel);
		return db.insert(DATABASE_TABLE, null, ini);
	}
	
	public boolean deleteTitle(long rowId)
	{
		return db.delete(DATABASE_TABLE, KEY_ID+"="+rowId,null )>0;
	}
	
	public Cursor getAllTitles()
	{
		return db.query(DATABASE_TABLE, new String[] {
				KEY_ID,NAME,ADDRESS,TEL},
				null, null, null, null, null);
	}
	
	public Cursor getTitle(long rowId) throws SQLException
	{
		Cursor mc=db.query(true, DATABASE_TABLE, new String[]{KEY_ID,NAME,ADDRESS,TEL}, 
				KEY_ID+"="+rowId, null, null, null, null, null);
		if(mc!=null)
			mc.moveToFirst();
		return mc;
	}
	
	public boolean updateTitle(long rowId,String name,String addr,String tel)
	{
		ContentValues args=new ContentValues();
		args.put(NAME, name);
		args.put(ADDRESS, addr);
		args.put(TEL, tel);
		return db.update(DATABASE_TABLE, args, KEY_ID+"="+rowId, null)>0;
	}

}
