package com.apps.pixwall

import android.app.Application
import android.util.Log
import com.ad.maxlibrary.MaxInitManager
import com.apps.pixwall.data.AppDataBase
import com.apps.pixwall.data.PaperDao
import com.apps.pixwall.util.ConvertUtil
import com.up.uploadlibrary.UpLoadManager

import java.io.IOException


class IApplication : 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 {
        var categoryList: MutableList<String> = mutableListOf()
        var isDataInitialized = false
            private set
    }

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

        MaxInitManager.init(
            this,
            "yJTWDCm78XKS7ZWNAryZTPQTiWmrXr6kxJrWr2hUxLLMI7Lr0KTvdUB7RRHoRPKf1SiyXSCaUZx3Xp8CSZKa_8",
            "22e1d07c7cb039bd",
            "807b12d65e0d3f15",
            "437eadd9d827b54c",
            "MAX_LOG"
        )
        UpLoadManager.init(this, "UP_LOG")

    }

    private fun initializeData(paperDao: PaperDao) {
        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 = ConvertUtil.getConvert(inputStream)
                Log.d("DataInit", "Loaded JSON for $name")

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

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

                    // 解析数据
                    val papers = ConvertUtil.getData(jsonData, categoryName)

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

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