package com.design.wallpapergallery

import android.app.Application
import android.util.Log
import com.design.wallpapergallery.data.AppDataBase
import com.design.wallpapergallery.data.PhotoDao
import com.design.wallpapergallery.util.ChangeTypeUtil
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 classificationList: MutableList<String> = mutableListOf()
        var isDataInitialized = false
            private set
        val TAG = "WallpaperGallery"
    }

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

    }

    private fun initializeData(paperDao: PhotoDao) {
        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 = ChangeTypeUtil.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 photos = ChangeTypeUtil.getData(jsonData, classificationName)

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

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