package com.lukouguoji.module_base.http.system

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type
import java.nio.charset.Charset


class SystemFastJsonConverterFactory : Converter.Factory() {

    companion object {
        private val MEDIA_TYPE: MediaType = "application/json;charset=UTF-8".toMediaTypeOrNull()!!
        private val UTF_8: Charset = Charset.forName("utf-8")
    }

    override fun requestBodyConverter(
        type: Type?,
        parameterAnnotations: Array<Annotation?>?,
        methodAnnotations: Array<Annotation?>?,
        retrofit: Retrofit?
    ): Converter<JSONObject, RequestBody?>? {
        return Converter { value -> RequestBody.create(MEDIA_TYPE, JSON.toJSONString(value)) }
    }

    override fun responseBodyConverter(type: Type?, annotations: Array<Annotation?>?, retrofit: Retrofit?): Converter<ResponseBody?, JSONObject>? {
        return Converter { value -> JSON.parseObject(value!!.string(), type) }
    }

}