package org.ccci.gto.android.common.stetho.db;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.support.annotation.NonNull;

import com.facebook.stetho.inspector.database.DatabaseConnectionProvider;
import com.facebook.stetho.inspector.database.DatabaseFilesProvider;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SQLiteOpenHelperStethoDatabaseProvider implements DatabaseFilesProvider, DatabaseConnectionProvider {
    private final List<File> mFiles;
    private final Map<File, SQLiteOpenHelper> mDatabases;

    public SQLiteOpenHelperStethoDatabaseProvider(@NonNull final SQLiteOpenHelper... helpers) {
        // create an indexed map of databases
        mDatabases = new HashMap<>(helpers.length);
        for (final SQLiteOpenHelper helper : helpers) {
            final File file;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                file = new File(helper.getDatabaseName());
            } else {
                file = new File(helper.getClass().toString());
            }

            mDatabases.put(file, helper);
        }

        // generate sorted list of databases
        mFiles = new ArrayList<>(mDatabases.keySet());
        Collections.sort(mFiles);
    }

    @Override
    public List<File> getDatabaseFiles() {
        return mFiles;
    }

    @Override
    public SQLiteDatabase openDatabase(File file) throws SQLiteException {
        return mDatabases.get(file).getWritableDatabase();
    }
}

@@ -41,16 +41,48 @@
 ho.db;%0A%0A
+import android.content.Context;%0A
 import a
@@ -120,16 +120,16 @@
 tabase;%0A
-
 import a
@@ -284,16 +284,60 @@
 NonNull;
+%0Aimport android.support.annotation.Nullable;
 %0A%0Aimport
@@ -400,24 +400,24 @@
 onProvider;%0A
-
 import com.f
@@ -472,16 +472,84 @@
 rovider;
+%0Aimport com.facebook.stetho.inspector.database.SqliteDatabaseDriver;
 %0A%0Aimport
@@ -1697,32 +1697,46 @@
  mFiles;%0A    %7D%0A%0A
+    @Nullable%0A
     @Override%0A  
@@ -1725,32 +1725,32 @@
 e%0A    @Override%0A
-
     public SQLit
@@ -1820,56 +1820,293 @@
     
-return mDatabases.get(file).getWritableDatabase(
+final SQLiteOpenHelper helper = mDatabases.get(file);%0A        return helper != null ? helper.getWritableDatabase() : null;%0A    %7D%0A%0A    @NonNull%0A    public SqliteDatabaseDriver toDatabaseDriver(@NonNull final Context context) %7B%0A        return new SqliteDatabaseDriver(context, this, this
 );%0A 

add toDatabaseDriver method and fix a potential NPE