package aicare.net.cn.sdk.ailinksdkdemoandroid.utils;

import android.content.Context;
import android.content.res.AssetManager;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * json装载机
 *
 * @author xing
 * @date 2024/04/29
 */
public class JsonLoader {

    public static JSONObject loadJSONFromAsset(Context context, String fileName) {
        JSONObject jsonObject = null;
        AssetManager manager = context.getAssets();
        try (InputStream is = manager.open(fileName);
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            jsonObject = new JSONObject(sb.toString());
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


    public static Map<String, String> loadJsonFromAsset(Context context, String fileName) {
        JSONObject jsonObject = loadJSONFromAsset(context, fileName);
        Map<String, String> map = new HashMap<>();
        try {
            if (jsonObject != null) {
                JSONArray dataList = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataList.length(); i++) {
                    JSONObject data = dataList.getJSONObject(i);
                    String nameEn = data.getString("name");
                    String nameZh = nameEn;
                    if (data.has("nameNew")) {
                        nameZh = data.getString("nameNew");
                    }
                    map.put(nameEn, nameZh);
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return map;
    }
}