package com.key.vibekeyboard.utils;

import android.content.res.AssetManager;

import com.key.vibekeyboard.MyApplication;
import com.key.vibekeyboard.data.bean.Category;
import com.key.vibekeyboard.data.database.entity.WallpaperInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class JsonUtils {

    private static JSONArray loadJSONFromAsset(String filename) {
        String json;
        try {
            AssetManager assetManager = MyApplication.getContext().getAssets();
            InputStream inputStream = assetManager.open(filename);
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            int i = inputStream.read(buffer);
            inputStream.close();
            json = new String(buffer, StandardCharsets.UTF_8);
            return new JSONArray(json);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static List<Category> parseJson(String filename) {
        List<Category> categories = new ArrayList<>();
        try {
            JSONArray jsonObject = loadJSONFromAsset(filename);
            for (int a = 0; a < Objects.requireNonNull(jsonObject).length(); a++) {
                JSONObject list = jsonObject.getJSONObject(a);
                Category myData = new Category();
                List<WallpaperInfo> wallpaperInfos = new ArrayList<>();
                myData.setClassName(list.getString("className"));
                JSONArray classArray = list.getJSONArray("list");
                for (int i = 0; i < classArray.length(); i++) {
                    JSONObject item = classArray.getJSONObject(i);
                    WallpaperInfo wallpaperInfo = new WallpaperInfo();
                    wallpaperInfo.setDownloaded(false);
                    wallpaperInfo.setIslike(false);
                    wallpaperInfo.setClassName(myData.getClassName());
                    wallpaperInfo.setPreview(item.getString("preview"));
                    wallpaperInfo.setThumb(item.getString("thumb"));
                    wallpaperInfo.setTitle(item.getString("title"));
                    wallpaperInfo.setZipUrl(item.getString("zipUrl"));
                    wallpaperInfos.add(wallpaperInfo);
                }
                myData.setList(wallpaperInfos);
                categories.add(myData);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return categories;
    }

}
