package com.zaojiao.app.core.http.converter

import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.zaojiao.app.core.http.common.NetResult
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

class ResultConverterFactory private constructor(
    private val moshi: Moshi,
) : Converter.Factory() {
    companion object {
        fun create(moshi: Moshi): ResultConverterFactory {
            return ResultConverterFactory(moshi)
        }
    }

    override fun responseBodyConverter(
        type: Type, annotations: Array<Annotation>, retrofit: Retrofit
    ): Converter<ResponseBody, *> {
        val responseType = Types.newParameterizedType(NetResult::class.java, type)
        val adapter: JsonAdapter<NetResult<*>> = moshi.adapter(responseType)
        return NetResultConverter(adapter)
    }

    private inner class NetResultConverter<T> constructor(
        private val adapter: JsonAdapter<NetResult<T>>
    ) : Converter<ResponseBody, NetResult<T>> {
        override fun convert(value: ResponseBody): NetResult<T>? {
            val json = value.string()
            return adapter.fromJson(json)
        }
    }
}