package com.wallpaper.perfectwallpaper.utils;

import android.util.Log;

import com.wallpaper.perfectwallpaper.MyApplication;
import com.wallpaper.perfectwallpaper.room.Category;
import com.wallpaper.perfectwallpaper.room.ImageEntry;

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 JsonParse {

    private static String loadJSONFromAsset(String fileName) {
        StringBuilder jsonString = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(MyApplication.getContext().getAssets().open(fileName)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d("JsonParse", "Loaded JSON: " + jsonString.toString());
        return jsonString.toString();
    }

    public static List<Category> parseJson(String fileName) {
        List<Category> categoryList = new ArrayList<>();
        try {
            String jsonString = loadJSONFromAsset(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");
                List<ImageEntry> imageList = new ArrayList<>();

                for (int j = 0; j < listArray.length(); j++) {
                    JSONObject imageObject = listArray.getJSONObject(j);
                    String original = imageObject.getString("original");
                    String previewThumb = imageObject.getString("previewThumb");
                    String source = imageObject.getString("source");

                    imageList.add(new ImageEntry(original, previewThumb, source, name, false));
                }

                categoryList.add(new Category(name, imageList));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return categoryList;
    }



}
