package com.abbidot.tracker.database

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.abbidot.tracker.MyApplication
import com.abbidot.tracker.bean.CreditCardBean
import com.abbidot.tracker.bean.DeviceBean
import com.abbidot.tracker.database.dao.CreditCardDao
import com.abbidot.tracker.database.dao.DeviceDao

/**
 *Created  by .yzq on 2021/11/6/006.
 * @link
 * @description:RoomDatabase实例
 */
//exportSchema = false,防止改数据库内容版本自动增加
@Database(
    entities = [DeviceBean::class, CreditCardBean::class],
    version = 5,
//    autoMigrations = [AutoMigration(from = 1, to = 2)],
    exportSchema = false,
)
abstract class MyDatabase : RoomDatabase() {
    abstract fun deviceDao(): DeviceDao
    abstract fun creditCardDao(): CreditCardDao

    companion object {

        //https://blog.csdn.net/shulianghan/article/details/131040728
//        val MIGRATION_1_2 = object : Migration(1, 2) {
//            override fun migrate(database: SupportSQLiteDatabase) {
//                // 执行从旧版本升级到新版本的 SQL 语句
////                database.execSQL("ALTER TABLE $DeviceTableName ADD COLUMN new_column INTEGER DEFAULT 0 NOT NULL")
////                database.execSQL("ALTER TABLE $CreditCardTableName ADD COLUMN new_column INTEGER DEFAULT 0 NOT NULL")
//                database.execSQL("CREATE TABLE $MessageTableName(messageId TEXT NOT NULL PRIMARY KEY,title TEXT,message TEXT,sendTime TEXT,messageType INTEGER,imgUrl TEXT,isRead BIT)")
//            }
//        }

        //MyDatabase单例模式
        private val db: MyDatabase by lazy {
            Room.databaseBuilder(MyApplication.instance, MyDatabase::class.java, "tracker_dp")
//                .addMigrations(MIGRATION_1_2)
                .fallbackToDestructiveMigration()//删除旧表格并创建新表格,的方式升级数据库版本
                .build()
        }

        //表名
        const val CREDIT_CARD_TABLE = "creditCard"
        const val DEVICE_TABLE = "device"

        fun deviceDao(): DeviceDao {
            return db.deviceDao()
        }

        fun creditCardDao(): CreditCardDao {
            return db.creditCardDao()
        }
    }
}