package com.ytpm.hydtw.utils

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ytpm.hydtw.dao.IdiomStory

object JsonReader {

    /**
     * 从 assets 目录读取 JSON 文件内容
     */
    fun readJsonFromAssets(context: Context, fileName: String): String? {
        return try {
            val inputStream = context.assets.open(fileName)
            val size = inputStream.available()
            val buffer = ByteArray(size)
            inputStream.read(buffer)
            inputStream.close()
            String(buffer, Charsets.UTF_8)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 解析 JSON 字符串为成语故事列表
     */
    fun parseIdiomStories(jsonString: String): List<IdiomStory> {
        val type = object : TypeToken<List<IdiomStory>>() {}.type
        return Gson().fromJson(jsonString, type)
    }
}