package com.prank.funnypranksounds.utils;

import android.util.Log;

import com.prank.funnypranksounds.MyApplication;
import com.prank.funnypranksounds.data.local.entity.AudioData;

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;
import java.util.Locale;

public class JsonParser {

    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();
        }
        return jsonString.toString();
    }

    public static List<AudioData> parseJson(String fileName) {
        List<AudioData> audioDataList = 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("categoryName");
                String url = categoryObject.getString("categoryUrl");

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

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

                    String title = itemObject.getString("title");
                    String mp3Url = itemObject.getString("mp3Url");
                    String preUrl = itemObject.getString("preUrl");

                    audioDataList.add(new AudioData(name, url, title, mp3Url, preUrl, false,false));
                }
            }

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

        return audioDataList;
    }

}
