package com.swago.baseswago.http

import com.alibaba.fastjson.util.ParameterizedTypeImpl
import com.swago.baseswago.util.LogUtil.d
import com.google.gson.Gson
import okhttp3.ResponseBody
import kotlin.Throws
import com.swago.baseswago.model.HttpResponseModel
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Converter
import java.io.IOException
import java.lang.reflect.Type

class JsonResponseBodyConverter<T>(
    private val gson: Gson,
    private val type: Type,
    private val annotations: Array<Annotation>
) : Converter<ResponseBody, T?> {
    @Throws(IOException::class)
    override fun convert(value: ResponseBody): T? {
        val response = value.string()
        try {
            val jsonObject = JSONObject(response)
            val status = jsonObject.getBoolean("status")
            if (!status) {
                throw SwagoException(jsonObject.getInt("code"), jsonObject.getString("msg"))
            }

            if (type.toString().contains("HttpResponseModel")) {
                val baseBean = gson.fromJson<HttpResponseModel<*>>(response, type)
                return baseBean as T
            }
            val p = ParameterizedTypeImpl(
                arrayOf(
                    type
                ), HttpResponseModel::class.java, HttpResponseModel::class.java
            )
            val baseBean = gson.fromJson<HttpResponseModel<*>>(response, p)
            return baseBean.data as T
        } finally {
            value.close()
        }
    }
}