package com.webtoonviewer.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(entities = [Book::class], version = 8)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun bookDao(): BookDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "app_database"
                ).addMigrations(MIGRATION_1_2).build()
                INSTANCE = instance
                instance
            }
        }

        private val MIGRATION_1_2 = object : Migration(7, 8) {
            override fun migrate(database: SupportSQLiteDatabase) {
//                // 1. 创建临时表
                database.execSQL(
                "CREATE TABLE books_temp (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                    "title TEXT NOT NULL, " +
                    "author TEXT NOT NULL, " +
                    "description TEXT NOT NULL, " +
                    "tag TEXT NOT NULL, " +
                    "img TEXT NOT NULL, " +
                    "chapters TEXT NOT NULL, " +
                    "chapterSum INTEGER NOT NULL, " +
                    "bookmarkChapter TEXT NOT NULL, " +
                    "bookmarkPosition INTEGER NOT NULL, " +
                    "bookmarkTopOffset INTEGER NOT NULL, " +
                    "isLocal INTEGER NOT NULL )"
                )

                // 2. 从旧表复制数据到新表
                database.execSQL("""
                    INSERT INTO books_temp (id, title, author, description, tag, img, chapters, chapterSum, bookmarkChapter, bookmarkPosition, bookmarkTopOffset, isLocal)
                    SELECT id, title, author, description, tag, img, chapters, chapterSum, bookmarkChapter, bookmarkPosition, bookmarkTopOffset, '0' FROM books
                    """)

                // 3. 删除旧表
                database.execSQL("DROP TABLE books")

                // 4. 将新表重命名为旧表
                database.execSQL("ALTER TABLE books_temp RENAME TO books")
            }

        }
    }
}