package se.emilsjolander.sprinkles;

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

import java.util.List;
import java.util.Map;

class DbOpenHelper extends SQLiteOpenHelper {
    private int baseVersion;

    protected DbOpenHelper(Context context, String databaseName, int baseVersion) {
        super(context, databaseName, null, Sprinkles.sInstance.mMigrations.size() + baseVersion);
        this.baseVersion = baseVersion;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        executeMigrations(db, baseVersion, Sprinkles.sInstance.mMigrations.size() + baseVersion);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        executeMigrations(db, oldVersion, newVersion);
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        db.execSQL("PRAGMA foreign_keys=ON;");
    }

    private void executeMigrations(SQLiteDatabase db, int oldVersion, int newVersion) {
        for (Map.Entry<Integer, List<Migration>> entry : Sprinkles.sInstance.mMigrations.entrySet()) {
            if (entry.getKey() > oldVersion && entry.getValue() != null) {
                int size = entry.getValue().size();
                for (int j = 0; j < size; j++) {
                    if (entry.getValue().get(j) != null) {
                        entry.getValue().get(j).execute(db);
                    }
                }
            }
        }
    }
}

@@ -411,49 +411,8 @@
 ull,
- Sprinkles.sInstance.mMigrations.size() +
  bas
@@ -418,24 +418,24 @@
 seVersion);%0A
+
         this
@@ -575,49 +575,8 @@
 ion,
- Sprinkles.sInstance.mMigrations.size() +
  bas
@@ -1084,32 +1084,33 @@
 %0A            if 
+(
 (entry.getKey() 
@@ -1121,16 +1121,61 @@
 dVersion
+%7C%7ColdVersion==newVersion)%0A                   
  && entr
@@ -1350,32 +1350,66 @@
 t(j) != null) %7B%0A
+                        try %7B%0A    
                 
@@ -1449,24 +1449,145 @@
 xecute(db);%0A
+                        %7Dcatch (Exception e)%7B%0A                            e.printStackTrace();%0A                        %7D%0A
             

update migration execute logic