package com.design.mischiefgo

import android.app.Application
import android.graphics.Typeface
import android.util.Log
import com.design.mischiefgo.entity.AppDataBase
import com.design.mischiefgo.entity.Usual
import com.design.mischiefgo.ut.CommonUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.IOException
import java.util.Collections;

class NewApp : Application() {
    companion object {
        lateinit var app: NewApp
        lateinit var typeface: Typeface
        var usuals: List<Usual>? = null
    }

    override fun onCreate() {
        super.onCreate()
        app = this
        CoroutineScope(Dispatchers.IO).launch {
            initializeDatabase()
        }
    }
    private fun initializeDatabase() {
        val database = AppDataBase.getDatabase(this)
        val infoDao = database.infoDao()

        try {
            typeface = Typeface.createFromAsset(assets, "lato_regular.ttf")
            val open = assets.open("prank.json")
            val string = CommonUtil.getString(open)

            if (string.isNotEmpty()) {
                usuals = CommonUtil.getUsual(string)
                Collections.shuffle(usuals)

                usuals?.forEach { category ->
                    Log.d("Database", "处理分类: ${category.name}")
                    // 使用Room的suspend函数或确保在IO线程
                    infoDao.insertAll(category.infolist)
                }
                Log.d("Database", "数据库初始化完成")
            }
        } catch (e: IOException) {
            Log.e("Database", "初始化失败", e)
        }
    }
}