package com.offline.music.player.helper;

import android.content.Context;

import com.offline.music.player.javabean.A_data.AudioItem;
import com.offline.music.player.javabean.A_data.Category;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class JsonUtils {

    // 读取 assets 中的 JSON 文件
    public static String readJsonFromAssets(Context context, String fileName) {
        StringBuilder jsonString = new StringBuilder();
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonString.toString();
    }

    // 解析 JSON 字符串并返回 Category 列表
    public static List<Category> parseJson(String jsonString) {
        List<Category> categories = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONArray jsonCategories = jsonObject.getJSONArray("categories");

            for (int i = 0; i < jsonCategories.length(); i++) {
                JSONObject categoryObject = jsonCategories.getJSONObject(i);
                String categoryName = categoryObject.getString("name");
                List<AudioItem> audios = new ArrayList<>();

                JSONArray jsonAudios = categoryObject.getJSONArray("audios");
                for (int j = 0; j < jsonAudios.length(); j++) {
                    JSONObject audioObject = jsonAudios.getJSONObject(j);
                    AudioItem audioItem = new AudioItem(
                            audioObject.getString("name"),
                            audioObject.getString("file"),
                            audioObject.getString("image")
                    );
                    audios.add(audioItem);
                }

                categories.add(new Category(categoryName, audios));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return categories;
    }
}


