package com.wall.engine.wallpaper;

import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;

public class JsonUtils {

    public static List<WallpaperItem> loadWallpapersFromJson(Context context, String fileName) {
        try {
            String jsonString = loadJSONFromAsset(context, fileName);
            Gson gson = new Gson();
            Type listType = new TypeToken<List<WallpaperItem>>(){}.getType();
            List<WallpaperItem> items = gson.fromJson(jsonString, listType);

            // 新增：确保每个item都有有效的ID
            if (items != null) {
                for (WallpaperItem item : items) {
                    ensureItemHasId(item);
                }
            }

            return items;
        } catch (Exception e) {
            Log.e("JsonUtils", "Error loading JSON from " + fileName, e);
            return null;
        }
    }

    private static String loadJSONFromAsset(Context context, String fileName) {
        String json;
        try {
            InputStream is = context.getAssets().open(fileName);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }


    private static void ensureItemHasId(WallpaperItem item) {
        if (item != null && item.getUrls() != null) {
            // 如果item没有设置id，或者id为空，则生成一个
            try {
                // 使用反射检查id字段是否为空
                java.lang.reflect.Field idField = WallpaperItem.class.getDeclaredField("id");
                idField.setAccessible(true);
                String currentId = (String) idField.get(item);

                if (currentId == null || currentId.isEmpty()) {
                    // 使用regular URL的hashCode作为唯一ID
                    String regularUrl = item.getUrls().getRegular();
                    if (regularUrl != null) {
                        String generatedId = "img_" + Math.abs(regularUrl.hashCode());
                        idField.set(item, generatedId);
                    }
                }
            } catch (Exception e) {
                Log.e("JsonUtils", "Error ensuring item ID", e);
            }
        }
    }
}