package cgmblelib.database;

import android.content.Context;
import android.os.Environment;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

import java.io.File;

import cgmblelib.database.dao.DaoDevice;
import cgmblelib.database.dao.DaoGlucose;
import cgmblelib.database.entity.PocDevice;
import cgmblelib.database.entity.PocGlucose;
import cgmblelib.utils.MyLog;

/**
 * Created by chumming on 2018/8/21.
 * @author minyuchun
 */
@Database(entities = {PocDevice.class, PocGlucose.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    private static boolean isExternalTestDatabase = false;

    private static volatile AppDatabase INSTANCE;

    public abstract DaoDevice mDaoDevice();
    public abstract DaoGlucose mDaoGlucose();


    public static AppDatabase getInMemoryDatabase(Context context) {
        if (INSTANCE == null) {
            synchronized(AppDatabase.class){
                if (INSTANCE == null){
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class,getDatabase())
                            .allowMainThreadQueries()
                            .addCallback(new Callback() {
                                @Override
                                public void onCreate(@NonNull SupportSQLiteDatabase db) {
                                    super.onCreate(db);
                                }

                                @Override
                                public void onOpen(@NonNull SupportSQLiteDatabase db) {
                                    super.onOpen(db);
                                    MyLog.d("数据库打开");
                                }
                            })
                            .build();
                }
            }

        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }

    private static String getDatabase(){
        if (isExternalTestDatabase){
            File externalFile = Environment.getExternalStorageDirectory();
            if (externalFile != null){
                String folder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/database/";
                File dirFirstFolder = new File(folder);
                boolean isFileExist = dirFirstFolder.exists();
                if (!isFileExist) {
                    isFileExist = dirFirstFolder.mkdirs();
                }
                if (isFileExist){
                    return folder + "database.db";
                }
            }
        }
        return "database.db";
    }
}
