package com.design.zenspace

import android.app.Application
import android.util.Log
import com.design.zenspace.entity.AppDataBase
import com.design.zenspace.entity.FeatureDao
import com.design.zenspace.environment.ad.AdActivityManager
import com.design.zenspace.environment.jb.MagicLockManager
import com.design.zenspace.tools.SaveUtil
import java.io.IOException


class DApplication : Application() {
    private val animaLs = "Animals.json"
    private val experiment = "Experimental.json"
    private val film = "Film.json"
    private val nature = "Nature.json"
    private val patterns = "Patterns.json"
    private val street = "Street.json"
    private val travel = "Travel.json"
    private val wallpaper = "Featured.json"

    companion object {
        const val TAG = "DApplication"
        var classificationList: MutableList<String> = mutableListOf()
        var isDataInitialized = false
            private set
    }

    override fun onCreate() {
        super.onCreate()
        val database = AppDataBase.getDatabase(this)
        val paperDao = database.featureDao()
        Thread {
            initializeData(paperDao)
            isDataInitialized = true
        }.start()

        AdActivityManager.instance.setControl(this)
        MagicLockManager.init(this)
    }

    private fun initializeData(paperDao: FeatureDao) {
        val names = arrayOf(animaLs, travel, experiment, film, nature, patterns, street, wallpaper)
        val startTime = System.currentTimeMillis()

        for (name in names) {
            try {
                // 在后台线程读取文件
                val inputStream = assets.open(name)
                val jsonData = SaveUtil.getConvert(inputStream)
                Log.d("DataInit", "Loaded JSON for $name")

                if (jsonData.isNotEmpty()) {
                    val classificationName = name.substring(0, name.indexOf("."))

                    // 同步添加分类名称（线程安全）
                    synchronized(classificationList) {
                        classificationList.add(classificationName)
                    }

                    // 解析数据
                    val feature = SaveUtil.getData(jsonData, classificationName)

                    // 批量插入数据
                    if (feature.isNotEmpty()) {
                        // 使用批量插入方法
                        paperDao.insertAll(feature)
                        Log.d("DataInit", "[$classificationName] insert ${feature.size} data")
                    }
                }
            } catch (e: IOException) {
                Log.e("DataInit", " $name error", e)
            }
        }

        val duration = System.currentTimeMillis() - startTime
        Log.d("DataInit", "use time: ${duration}ms")
    }
}