package com.quyunshuo.module.home.utils

import android.content.Context
import com.google.common.base.CharMatcher.`is`


object AssetManager {
    @Volatile
    private var singleton: AssetManager? = null

    val instance: AssetManager?
        get() {
            if (singleton == null) {
                synchronized(AssetManager::class.java) {
                    if (singleton == null) {
                        singleton = AssetManager
                    }
                }
            }
            return singleton
        }

    fun readJsonFromAssets(context: Context, fileName: String): String? {
        /* return try {
             // 通过 AssetManager 打开文件流
             context.assets.open(fileName).bufferedReader().use {
                 it.readText()
             }
         } catch (e: IOException) {
             ""
         }*/
        try {
            var input = context.assets.open(fileName)
            var size = input.available();
            val buffer = ByteArray(size)
            input.read(buffer)
            input.close()
            val json = String(buffer, charset("UTF-8"))
            return json.replace("\r","").replace("\n","").replace(" ","").replace("\\\"", "\"")
        } catch (e: Exception) {
            return ""
        }
    }

    /* fun readJsonFromAssets(context: Context, fileName: String?): String {
         val jsonContent = StringBuilder()

         try {
             val assetManager: AssetManager = context.assets
             assetManager.open(fileName).use { inputStream ->
                 BufferedReader(InputStreamReader(inputStream)).use { reader ->
                     var line: String?
                     while ((reader.readLine().also { line = it }) != null) {
                         jsonContent.append(line) // readLine()自动去除行尾换行符
                     }
                 }
             }
         } catch (e: IOException) {
             e.printStackTrace()
         }
         return jsonContent.toString().replace("\r\n", "") // 全局替换剩余换行符
     }*/
}