package com.wallpaper.wallpaperbox.util;

import android.content.Context;

import com.wallpaper.wallpaperbox.data.entity.WallpaperEntity;

import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class JsonUtil {

    private static String loadJSONFromAsset(Context context, String fileName) {
        StringBuilder jsonString = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    context.getAssets().open(fileName)));
            String line;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonString.toString();
    }

    public static List<WallpaperEntity> parseJson(Context context, String fileName) {
        List<WallpaperEntity> wallPaperList = new ArrayList<>();
        try {
            String jsonString = loadJSONFromAsset(context, fileName);
            if (jsonString.isEmpty()) {
                throw new IllegalArgumentException("JSON file is empty or invalid.");
            }

            JSONArray jsonArray = new JSONArray(jsonString);

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject categoryObject = jsonArray.getJSONObject(i);

                String name = categoryObject.getString("name");

                JSONArray listArray = categoryObject.getJSONArray("data");

                for (int j = 0; j < listArray.length(); j++) {
                    JSONObject itemObject = listArray.getJSONObject(j);

                    String original = itemObject.getString("original");
                    String previewThumb = itemObject.getString("previewThumb");
                    String source = itemObject.getString("source");

                    wallPaperList.add(new WallpaperEntity(name, original, previewThumb, source, false));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return wallPaperList;
    }
}
