package com.tencent.liteav.demo.superplayer.database

import android.content.Context
import android.util.Log
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.tencent.liteav.demo.superplayer.database.dao.CountDownDao
import com.tencent.liteav.demo.superplayer.database.dao.HistoryDao
import com.tencent.liteav.demo.superplayer.database.entity.CountDown
import com.tencent.liteav.demo.superplayer.database.entity.History

@Database(
    version = 4,
    entities = [History::class, CountDown::class],
    exportSchema = true,
)
abstract class PlayerDatabase : RoomDatabase() {
    abstract fun historyDao(): HistoryDao
    abstract fun countDownDao(): CountDownDao

    companion object {
        // Singleton prevents multiple instances of database opening at the
        // same time.
        @Volatile
        private var INSTANCE: PlayerDatabase? = null

        @JvmStatic
        fun getDatabase(context: Context): PlayerDatabase {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    PlayerDatabase::class.java,
                    "player_database"
                ).addMigrations(migration1_2, migration2_3, migration3_4).build()
                INSTANCE = instance
                // return instance
                instance
            }
        }

        private val migration1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE `History` ADD COLUMN `section_id` TEXT;")
            }
        }

        private val migration2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE `History` ADD COLUMN `date` TEXT;")
            }
        }

        private val migration3_4 = object : Migration(3, 4) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("DELETE FROM `History`;")
                database.execSQL("DELETE FROM `CountDown`;")
            }
        }
    }
}