package com.xtremelabs.robolectric.shadows;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

import com.xtremelabs.robolectric.util.Implementation;
import com.xtremelabs.robolectric.util.Implements;
import com.xtremelabs.robolectric.util.RealObject;

/**
 * Shadow for {@code SQLiteOpenHelper}.  Provides basic support for retrieving
 * databases and partially implements the subclass contract.  (Currently,
 * support for {@code #onUpgrade} is missing).
 *
 */
@Implements(SQLiteOpenHelper.class)
public class ShadowSQLiteOpenHelper {
	
	@RealObject private SQLiteOpenHelper realHelper;
	private static SQLiteDatabase db;
	
	public void __constructor__(Context context, String name,
				CursorFactory factory, int version) {
		// clear out static data
		if ( db != null ) {
			db.close();
		}
		db = null;
	}
	
	@Implementation
	public synchronized void close() {
		if ( db != null ) {
			db.close();
		}
		db = null;
	}
	
	@Implementation
	public synchronized SQLiteDatabase getReadableDatabase() {
		SQLiteDatabase thisDb = SQLiteDatabase.openDatabase("path", null, 0);
		if ( db == null ) {
			realHelper.onCreate( thisDb );
		}
		realHelper.onOpen( thisDb );
		db = thisDb;
		return db;
	}
	
	@Implementation
	public synchronized SQLiteDatabase getWritableDatabase() {
		SQLiteDatabase thisDb = SQLiteDatabase.openDatabase("path", null, 0);

		if ( db == null ) {
			realHelper.onCreate( thisDb );
		}
		realHelper.onOpen( thisDb );
		db = thisDb;
		return db;
	}

}

@@ -1128,32 +1128,55 @@
 bleDatabase() %7B%0A
+%09%09if ( db == null ) %7B%0A%09
 %09%09SQLiteDatabase
@@ -1168,38 +1168,37 @@
 %09SQLiteDatabase 
-thisDb
+newDB
  = SQLiteDatabas
@@ -1236,66 +1236,61 @@
 ;%0A%09%09
-if ( db == null ) %7B%0A%09%09%09realHelper.onCreate( thisDb )
+%09realHelper.onCreate( newDB );%0A%09%09%09db = newDB
 ;%0A%09%09%7D%0A
+%09%09%0A
 %09%09re
@@ -1306,39 +1306,20 @@
 onOpen( 
-thisDb );%0A%09%09db = thisDb
+db )
 ;%0A%09%09retu
@@ -1407,16 +1407,39 @@
 ase() %7B%0A
+%09%09if ( db == null ) %7B%0A%09
 %09%09SQLite
@@ -1447,22 +1447,21 @@
 atabase 
-thisDb
+newDB
  = SQLit
@@ -1504,31 +1504,8 @@
  0);
-%0A%0A%09%09if ( db == null ) %7B
 %0A%09%09%09
@@ -1529,66 +1529,62 @@
 te( 
-thisDb );%0A%09%09%7D%0A%09%09realHelper.onOpen( thisDb );%0A%09%09db = thisDb
+newDB );%0A%09%09%09db = newDB;%0A%09%09%7D%0A%0A%09%09realHelper.onOpen( db )
 ;%0A%09%09

Fix database instance on successive calls to getWritableDatabase and its read twin