package com.yidianling.ydlcommon.custom.http;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.yidianling.common.tools.LogUtil;
import okhttp3.ResponseBody;
import retrofit2.Converter;

import java.io.IOException;
import java.io.StringReader;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String resp = value.string();
        LogUtil.d("resp: " + resp);
        BaseResponse response = gson.fromJson(resp, BaseResponse.class);
        JsonReader reader = new JsonReader(new StringReader(resp));
        try {
            return adapter.read(reader);
        } catch (Exception e) {
            LogUtil.e("catch Exception!!!");
            throw new ResultException(response.code, response.msg);
        } finally {
            value.close();
        }
    }

}