package com.secspace.lib.common.function.database

import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.Room
import android.arch.persistence.room.migration.Migration
import android.content.Context
import com.secspace.lib.common.function.database.dao.UseAppDao
import com.secspace.lib.common.function.database.dao.UseTimeDao
import com.secspace.lib.common.function.database.db.EduDatabase


class DatabaseManager private constructor(val context: Context) {
    private var mEduDatabase: EduDatabase? = null
    private var mUseAppDao: UseAppDao? = null
    private var mUseTimeDao: UseTimeDao? = null
    fun init() {
//        mEduDatabase = RoomCipher.databaseBuilder(context, EduDatabase::class.java, "edu_space.db", "skr123")
//                .fallbackToDestructiveMigration()
//                .allowMainThreadQueries()
//                .build()
        mEduDatabase = Room.databaseBuilder(context, EduDatabase::class.java, "edu_space.db")
                .fallbackToDestructiveMigration()
                .allowMainThreadQueries()
                .build()
        mUseAppDao = mEduDatabase?.useAppDao()
        mUseTimeDao = mEduDatabase?.useTimeDao()
    }

    fun getEduDatabase(): EduDatabase? {
        return mEduDatabase
    }

    fun getUseAppDao(): UseAppDao? {
        return mUseAppDao
    }

    fun getUseTimeDao(): UseTimeDao? {
        return mUseTimeDao
    }

    /**
     * 数据库版本 1->2 user表格新增了age列
     */
    private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
//            database.execSQL("ALTER TABLE target_app ADD COLUMN age integer")
        }
    }

    /**
     * 数据库版本 2->3 新增book表格
     */
    private val MIGRATION_2_3: Migration = object : Migration(2, 3) {
        override fun migrate(database: SupportSQLiteDatabase) {
//            database.execSQL(
//                    "CREATE TABLE IF NOT EXISTS `book` (`uid` INTEGER PRIMARY KEY autoincrement, `name` TEXT , `userId` INTEGER, 'time' INTEGER)")
        }
    }

    companion object {
        @Volatile
        private var instance: DatabaseManager? = null

        fun getInstance(context: Context): DatabaseManager {
            if (instance == null) {
                synchronized(DatabaseManager::class) {
                    if (instance == null) {
                        instance = DatabaseManager(context.applicationContext)
                    }
                }
            }
            return instance!!
        }
    }
}