package com.prankapp.fartsounds.airhorn.utilsfff;

import android.content.Context;

import com.prankapp.fartsounds.airhorn.model.PrankListModel;

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

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class JsonUtils {


    public static ArrayList<PrankListModel> parseJsonListFromAssets(Context context, String fileName) {
        ArrayList<PrankListModel> outerItems = new ArrayList<>();
        try (InputStream is = context.getAssets().open(fileName)) {
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            String jsonString = new String(buffer, "UTF-8");

            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                PrankListModel outerItem = new PrankListModel();
                outerItem.setCategoryUrl(jsonObject.getString("categoryUrl")) ;
                outerItem.setCategoryName(jsonObject.getString("categoryName"));
                outerItem.setCategoryId(jsonObject.getString("categoryId"));

                // 解析innerItems列表
                JSONArray innerJsonArray = jsonObject.getJSONArray("list");
                ArrayList<PrankListModel.ListBean> innerItemList = new ArrayList<>();
                for (int j = 0; j < innerJsonArray.length(); j++) {
                    JSONObject innerJsonObject = innerJsonArray.getJSONObject(j);
                    PrankListModel.ListBean innerItem = new PrankListModel.ListBean();
                    innerItem.setPreUrl(innerJsonObject.getString("preUrl")) ;
                    innerItem.setMp3Url(innerJsonObject.getString("mp3Url"));
                    innerItem.setTitle(innerJsonObject.getString("title"));
                    innerItemList.add(innerItem);
                }
                outerItem.setList(innerItemList);;

                outerItems.add(outerItem);
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return outerItems;
    }



}
