package com.yidian.bcommon.utils

import android.content.Context
import android.content.res.AssetManager
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import org.json.JSONObject

import org.json.JSONArray


/**
 * JSON解析工具类
 */
object JsonUtils {

  //从文件中读取内容转成json字符串
  fun file2JsonStr(context: Context, fileName: String): String? {
    val stringBuilder = StringBuilder()
    try {
      val assetManager: AssetManager = context.assets
      val isr = InputStreamReader(assetManager.open(fileName))
      val bf = BufferedReader(isr)
      var line: String?
      while (bf.readLine().also { line = it } != null) {
        stringBuilder.append(line)
      }
      bf.close()
      isr.close()
      return stringBuilder.toString()
    } catch (e: IOException) {
      e.printStackTrace()
    }
    return null
  }

  /**
   * 将json对象转换为HashMap
   * @param json
   * @return
   */
  fun parseJSON2MapNull(json: JSONObject): Map<String, Any?> {
    val map: MutableMap<String, Any> = HashMap()
    // 最外层解析
    for (k in json.keys()) {
      when (val v = json[k]) {
        is JSONArray -> {// 如果内层还是json数组的话，继续解析
          val list: MutableList<Map<String, Any?>> = ArrayList()
          for (i in 0 until v.length()) {
            val jsonObject = v.getJSONObject(i)
            list.add(parseJSON2MapNull(jsonObject))
          }
          map[k.toString()] = list
        }
        is JSONObject -> {// 如果内层是json对象的话，继续解析
          map[k.toString()] = parseJSON2Map(v)
        }
        else -> {// 如果内层是普通对象的话，直接放入map中
          map[k.toString()] = v
        }
      }
    }
    return map
  }

  /**
   * 将json对象转换为HashMap
   * @param json
   * @return
   */
  fun parseJSON2Map(json: JSONObject): Map<String, Any> {
    val map: MutableMap<String, Any> = HashMap()
    // 最外层解析
    for (k in json.keys()) {
      when (val v = json[k]) {
        is JSONArray -> {// 如果内层还是json数组的话，继续解析
          val list: MutableList<Map<String, Any>> = ArrayList()
          for (i in 0 until v.length()) {
            val jsonObject = v.getJSONObject(i)
            list.add(parseJSON2Map(jsonObject))
          }
          map[k.toString()] = list
        }
        is JSONObject -> {// 如果内层是json对象的话，继续解析
          map[k.toString()] = parseJSON2Map(v)
        }
        else -> {// 如果内层是普通对象的话，直接放入map中
          map[k.toString()] = v
        }
      }
    }
    return map
  }

}
