package de.philipphager.disclosure.database;

import android.database.sqlite.SQLiteDatabase;
import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;
import javax.inject.Inject;
import rx.schedulers.Schedulers;

public class DatabaseManager {
  private final DatabaseOpenHelper openHelper;
  private final SqlBrite sqlBrite;
  private BriteDatabase readableDB;
  private SQLiteDatabase writeableDB;

  @Inject public DatabaseManager(DatabaseOpenHelper openHelper, SqlBrite sqlBrite) {
    this.openHelper = openHelper;
    this.sqlBrite = sqlBrite;
  }

  public BriteDatabase openReadable() {
    synchronized (this) {
      ensureDatabase();
      return readableDB;
    }
  }

  public SQLiteDatabase openWriteable() {
    synchronized (this) {
      ensureDatabase();
      return writeableDB;
    }
  }

  public void close() {
    synchronized (this) {
      if (readableDB != null) {
        readableDB.close();
        readableDB = null;
      }

      if (writeableDB != null) {
        writeableDB.close();
        writeableDB = null;
      }
    }
  }

  private void ensureDatabase() {
    if (readableDB == null) {
      readableDB = sqlBrite.wrapDatabaseHelper(openHelper, Schedulers.io());
    }

    if (writeableDB == null) {
      writeableDB = openHelper.getWritableDatabase();
    }
  }
}

@@ -368,20 +368,22 @@
 atabase 
-read
+observ
 ableDB;%0A
@@ -584,18 +584,19 @@
  public 
-Br
+SQL
 iteDatab
@@ -607,12 +607,13 @@
 open
-Read
+Write
 able
@@ -653,141 +653,78 @@
     
-ensureDatabase();%0A      return readableDB;%0A    %7D%0A  %7D%0A%0A  public SQLiteDatabase openWriteable() %7B%0A    synchronized (this) %7B%0A      ensur
+if (writeableDB == null) %7B%0A        writeableDB = openHelper.getWritabl
 eDat
@@ -728,24 +728,32 @@
 Database();%0A
+      %7D%0A
       return
@@ -796,16 +796,25 @@
 id close
+Writeable
 () %7B%0A   
@@ -842,28 +842,29 @@
 %7B%0A      if (
-read
+write
 ableDB != nu
@@ -873,28 +873,29 @@
 ) %7B%0A        
-read
+write
 ableDB.close
@@ -902,28 +902,29 @@
 ();%0A        
-read
+write
 ableDB = nul
@@ -938,156 +938,91 @@
   %7D%0A
-%0A
     
-  if (writeableDB != null) %7B%0A        writeableDB.close();%0A        writeableDB = null;%0A      %7D%0A    %7D%0A  %7D%0A%0A  private void ensureDatabase(
+%7D%0A  %7D%0A%0A  public BriteDatabase openObservable() %7B%0A    synchronized (this
 ) %7B%0A    
 if (
@@ -1021,16 +1021,20 @@
     
+  
 if (
-read
+observ
 able
@@ -1057,12 +1057,16 @@
     
-read
+  observ
 able
@@ -1136,95 +1136,210 @@
     
+  
 %7D
-%0A
 %0A    
-if (writeableDB == null) %7B%0A      write
+  return observableDB;%0A    %7D%0A  %7D%0A%0A  public void closeObservable() %7B%0A    synchronized (this) %7B%0A      if (observ
 ableDB 
+!
 = 
-openHelper.getWritableDatabase();
+null) %7B%0A        observableDB.close();%0A        observableDB = null;%0A      %7D
 %0A   

Restructure DatabaseManager