package com.gallery.free.wallpaper

import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.InputStream

object Utils_json {

    private val gson = Gson()
    private const val TAG = "JsonUtils"


    fun loadWallpapersFromAssets(context: Context, fileName: String): List<WallpaperJson> {
        return try {
            Log.d(TAG, "Loading wallpapers from: $fileName")

            // 检查文件是否存在
            val fileList = context.assets.list("")
            if (fileList?.contains(fileName) != true) {
                Log.e(TAG, "File not found in assets: $fileName")
                return emptyList()
            }

            val inputStream: InputStream = context.assets.open(fileName)
            val jsonString = inputStream.bufferedReader().use { it.readText() }

            if (jsonString.isBlank()) {
                Log.e(TAG, "Empty JSON file: $fileName")
                return emptyList()
            }

            val listType = object : TypeToken<List<WallpaperJson>>() {}.type
            val result = gson.fromJson<List<WallpaperJson>>(jsonString, listType)

            Log.d(TAG, "Successfully loaded ${result.size} wallpapers from $fileName")
            result
        } catch (e: Exception) {
            Log.e(TAG, "Error loading wallpapers from $fileName", e)
            emptyList()
        }
    }

    fun convertToWallpaperItem(wallpaperJson: WallpaperJson): WpItem {
        val name = wallpaperJson.altDescription ?: "Unknown"

        val smallUrl = wallpaperJson.urls.small
        val fullUrl = wallpaperJson.urls.full

        val finalSmallUrl = if (smallUrl.isEmpty()) {
            wallpaperJson.urls.small
        } else {
            smallUrl
        }
        val description = wallpaperJson.altDescription ?: wallpaperJson.user.name ?: ""

        return WpItem(
            smallUrl = finalSmallUrl,
            fullUrl = fullUrl,
            description = description
        )
    }
}