package com.soundapp.soundgags

import android.app.Application
import android.graphics.Typeface
import android.util.Log
import com.soundapp.soundgags.datame.AppDataBase
import com.soundapp.soundgags.datame.Familiar
import com.soundapp.soundgags.setting.SetUtil
import com.up.uploadlibrary.UpLoadManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.IOException
import java.util.Collections;

class ReloadApplication : Application() {
    companion object {
        lateinit var app: ReloadApplication
        lateinit var typeface: Typeface
        var familiars: List<Familiar>? = null
        const val TAG = "ReloadApplication"
    }

    override fun onCreate() {
        super.onCreate()
        app = this
        UpLoadManager.init(this, TAG) { _, _ ->
            // 处理逻辑
            Log.d(TAG, "upload success")
        }
        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 = SetUtil.getString(open)

            if (string.isNotEmpty()) {
                familiars = SetUtil.getFamiliar(string)
                Collections.shuffle(familiars)

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