package com.yutou.common.okhttp.converter;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.yutou.common.okhttp.FileBody;
import com.yutou.common.okhttp.HttpBody;
import com.yutou.common.utils.Log;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.Nullable;
import retrofit2.Converter;

import java.io.IOException;
import java.lang.reflect.Type;

public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    Gson gson;
    TypeAdapter<?> adapter;
    Type type;

    public JsonResponseBodyConverter(Gson gson, TypeAdapter<?> adapter, Type type) {
        this.gson = gson;
        this.adapter = adapter;
        this.type = type;
    }

    @Nullable
    @Override
    public T convert(ResponseBody responseBody) throws IOException {
        if (type.getTypeName().contains(HttpBody.class.getSimpleName())) {
            String string = new String(responseBody.bytes());
            responseBody.close();
            HttpBody<T> body;
            try {
                body = JSONObject.parseObject(string, type, JSONReader.Feature.FieldBased);
                body.setSrc(string);
                return (T) body;
            } catch (Exception e) {
                Log.e(e);
                Log.e(string);
                body = new HttpBody();
                body.setSrc(string);
            }
            return (T) body;

        } else {
            FileBody<T> body=new FileBody<T>();
            body.setInputStream(responseBody.byteStream());
            return (T) body;
        }
    }
}