package com.gh.gamecenter.gamedetail.accelerator

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
import com.gh.gamecenter.feature.entity.AcctGameInfo
import com.gh.gamecenter.feature.entity.AcctRecord
import com.gh.gamecenter.room.converter.AcctGameInfoConverter
import com.halo.assistant.HaloApp

@Database(
    entities = [AcctGameInfo::class, AcctRecord::class],
    version = 2,
    exportSchema = false
)
@TypeConverters(
    AcctGameInfoConverter::class
)
abstract class AccelerationDataBase : RoomDatabase() {

    abstract fun accelerationDao(): AccelerationDao

    companion object {
        private const val DATABASE_NAME: String = "acceleration_db"

        val instance: AccelerationDataBase by lazy { buildDatabase(HaloApp.getInstance().application) }

        private fun buildDatabase(context: Context): AccelerationDataBase {
            return Room.databaseBuilder(context, AccelerationDataBase::class.java, DATABASE_NAME)
                .addMigrations(MIGRATION_1_2)
                .allowMainThreadQueries()
                .build()
        }

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(db: SupportSQLiteDatabase) {
                // 删除表 AcctZoneListBean
                db.execSQL("DROP TABLE IF EXISTS AcctZoneListBean")
                // 创建新表的SQL ,游戏加速成功记录
                createAcctRecordTab(db)

                renamePrimaryKeyWithAcctGameInfoTab(db)

            }

            private fun createAcctRecordTab(db: SupportSQLiteDatabase) {
                db.execSQL(
                    """
                CREATE TABLE IF NOT EXISTS AcctRecord (
                    gameId TEXT PRIMARY KEY NOT NULL,
                    game TEXT NOT NULL,
                    zoneInfo TEXT NOT NULL,
                    hasMultiZone INTEGER NOT NULL,
                    createTime INTEGER NOT NULL
                )
            """
                )
            }

            /**
             * 重命名表 AcctGameInfo 主键
             * 游戏旧表中没有 gameId 字段，这里将旧表数据直接清空
             */
            private fun renamePrimaryKeyWithAcctGameInfoTab(db: SupportSQLiteDatabase) {
                // 1. 创建临时表（包含新的结构）
                db.execSQL(
                    """
                    CREATE TABLE IF NOT EXISTS AcctGameInfo_temp (
                        gameId TEXT PRIMARY KEY NOT NULL,
                        accGamePkgName TEXT NOT NULL,
                        zoneInfo TEXT NOT NULL,
                        notifyGameName TEXT,
                        notifyGameTxtTitle TEXT,
                        notifyGameSmallLogo INTEGER,
                        notifyGameLargeLogo INTEGER,
                        notifyClickParam TEXT
                    )
                """
                )

                // 2. 删除旧表
                db.execSQL("DROP TABLE AcctGameInfo")

                // 3. 重命名新表
                db.execSQL("ALTER TABLE AcctGameInfo_temp RENAME TO AcctGameInfo")
            }
        }
    }
}