package com.gh.vspace.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
import com.gh.vspace.db.VGameDatabase.Companion.DB_VERSION
import com.halo.assistant.HaloApp

@TypeConverters(VGameConverter::class)
@Database(entities = [VGameEntity::class, VArchiveEntity::class], version = DB_VERSION, exportSchema = false)
abstract class VGameDatabase : RoomDatabase() {

    abstract fun vGameDao(): VGameDao

    abstract fun vArchiveDao(): VArchiveDao

    companion object {
        const val DATABASE = "v_game_database.db"

        const val DB_VERSION = 2

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "CREATE TABLE VArchiveEntity (" +
                            "id TEXT NOT NULL PRIMARY KEY," +
                            "gameId TEXT NOT NULL," +
                            "name TEXT NOT NULL," +
                            "descContent TEXT NOT NULL," +
                            "url TEXT NOT NULL," +
                            "configUrl TEXT NOT NULL," +
                            "md5 TEXT NOT NULL," +
                            "time INTEGER NOT NULL," +
                            "type INTEGER NOT NULL," +
                            "filePath TEXT NOT NULL)"
                )
            }
        }

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

        private fun buildDatabase(context: Context): VGameDatabase {
            return Room.databaseBuilder(context, VGameDatabase::class.java, DATABASE)
                .addMigrations(MIGRATION_1_2)
                .fallbackToDestructiveMigration()
                .build()
        }
    }

}