package cn.muchinfo.rma.global.room;


import android.content.Context;

import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import cn.muchinfo.rma.global.database.AppDatabase;


/**
 * Builder
 *
 * @author a_liYa
 * @date 2017/8/7 20:47.
 */
public class Builder {

    private static RoomDatabase db;

    private static final String DATABASE_NAME = "db-goods_info";

    private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
            @Override
            public void migrate(SupportSQLiteDatabase database) {
                //此处对于数据库中的所有更新都需要写下面的代码
                if (database.isOpen()) {
                    database.execSQL("ALTER TABLE goods_infos "
                            + " ADD COLUMN currencyId INTEGER NOT NULL DEFAULT 0");
                }
            }
        };

    private static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            //此处对于数据库中的所有更新都需要写下面的代码
            if (database.isOpen()) {
                database.execSQL("ALTER TABLE goods_info "
                        + " ADD COLUMN goodsType INTEGER NOT NULL DEFAULT 0");
                database.execSQL("ALTER TABLE goods_info "
                        + " ADD COLUMN showBrokerFlag INTEGER NOT NULL DEFAULT 0");
                database.execSQL("ALTER TABLE goods_info "
                        + " ADD COLUMN quoteGear INTEGER NOT NULL DEFAULT 0");
            }
        }
    };

    private static final Migration MIGRATION_3_4 = new Migration(3, 4) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            //此处对于数据库中的所有更新都需要写下面的代码
            if (database.isOpen()) {
                database.execSQL("ALTER TABLE goods_info "
                        + " ADD COLUMN innerDealMode INTEGER NOT NULL DEFAULT 0");
            }
        }
    };





    public static <T extends RoomDatabase> RoomDatabase build(Context context, Class<T> database) {
        if (db == null) {
            synchronized (Builder.class) {
                if (db == null) {
                    db = Room.databaseBuilder(context, database, DATABASE_NAME)
                            .allowMainThreadQueries()
                            .build();
                }
            }
        }
        return db;
    }

    public static <T extends AppDatabase> T getDatabase() {
        return (T) db;
    }

}
