package com.ifavine.pay.api;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;


import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by tree on 1/4/2017.
 * 自定义响应ResponseBody
 */

public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson mGson;//gson对象
    private final TypeAdapter<T> adapter;

    /**
     * 构造器
     */
    public JsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.mGson = gson;
        this.adapter = adapter;
    }

    /**
     * 转换
     *
     * @param responseBody
     * @return
     * @throws IOException
     */
    @Override
    public T convert(ResponseBody responseBody) throws IOException {
        String data = null;
        try {
            //数据解密
            String d = responseBody.string().replaceAll("\\\\r\\\\n", "").replaceAll("\\\\", "");
            data = d.substring(1, d.length() - 1);
            Log.i("aaaaa", "response data：" + data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JsonReader jsonReader = mGson.newJsonReader(new InputStreamReader(getStringStream(data)));
        try {
            return adapter.read(jsonReader);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将一个字符串转化为输入流
     */
    public static InputStream getStringStream(String str) {
        if (str != null && !str.trim().equals("")) {
            try {
                ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes());
                return in;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

}
