package com.paperapp.lenscape

import android.app.Application
import android.util.Log
import com.paperapp.lenscape.element.AppDataBase
import com.paperapp.lenscape.element.ElementDao
import com.paperapp.lenscape.tools.ImagePreUtil
import com.up.uploadlibrary.UpLoadManager

import java.io.IOException


class DApp : 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 = "Elementd.json"

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

    override fun onCreate() {
        super.onCreate()
        UpLoadManager.init(this, TAG) { _, _ ->
            // 处理逻辑
            null
            Log.d(TAG, "upload success")
        }
        val database = AppDataBase.getDatabase(this)
        val paperDao = database.elementDao()
        Thread {
            initializeData(paperDao)
            isDataInitialized = true
        }.start()

    }

    private fun initializeData(paperDao: ElementDao) {
        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 = ImagePreUtil.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 element = ImagePreUtil.getData(jsonData, classificationName)

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

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