package com.qimai.android.fetch.convert

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.reflect.TypeToken
import com.qimai.android.fetch.interceptors.GsonParseError
import com.qimai.android.fetch.interceptors.ServerError
import com.qimai.android.fetch.interceptors.TokenExpire
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

/**
 *   created by wangwei   ON 2019-09-04  email:wangwei_5521@163.com
 *   @version 1.1.1
 *   @Description
 **/
@Suppress("UNCHECKED_CAST")
/**
 * @param gsonParseError gson解析异常
 */
class StandardGsonConvertFactory constructor(
    private var gson: Gson,
    var expire: TokenExpire?
) :
    Converter.Factory() {
    lateinit var adapter: TypeAdapter<out Any>

    companion object {
        fun create(gson: Gson): StandardGsonConvertFactory {
            if (gson == null) throw Throwable("gson == null")
            return StandardGsonConvertFactory(gson, null)
        }

        fun create(gson: Gson, expire: TokenExpire): StandardGsonConvertFactory {
            if (gson == null) throw Throwable("gson == null")
            return StandardGsonConvertFactory(gson, expire)
        }
    }

    override fun responseBodyConverter(
        type: Type,
        annotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *>? {
//        annotations.forEach {
//            if (it is Standard) {
//                val baseDataType = object : ParameterizedType {
//                    override fun getRawType(): Type {
//                        return BaseData::class.java
//                    }
//
//                    override fun getOwnerType(): Type? {
//                        return null
//                    }
//
//                    override fun getActualTypeArguments(): Array<Type> {
//                        return arrayOf(type)
//                    }
//
//                }
//                adapter = gson.getAdapter(TypeToken.get(baseDataType))
//                return StandardGsonResponseBodyConverter(adapter, gson)
//            }
//        }
        adapter = gson.getAdapter(TypeToken.get(type))
        return StandardGsonResponseBodyConverter(adapter, gson, type, expire)

    }

}
