package com.beanpodtech.allinone.utils;

import com.google.gson.Gson;
import com.lzy.okgo.callback.AbsCallback;

import okhttp3.Response;

public abstract class OkGoUtil<T> extends AbsCallback<T> {
    private Class<T> aClass;   // 传Entity
    private Gson gson = new Gson();

    public OkGoUtil(Class<T> aClass) {
        this.aClass = aClass;
    }

    @Override
    public T convertResponse(Response response) {
        T t = null;
        try {
            if (response.body() == null) {
                return null;
            }
            if (aClass == null) {
                return null;
            }
            String string = response.body().string();

            t = gson.fromJson(string, aClass);
        } catch (Exception e) {
            try {
                t = aClass.newInstance();
//                Looper.prepare();
//                ToastUtils.show(EduApplication.getContext(), "网络请求异常");
//                Looper.loop();
                return t;
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
                ex.printStackTrace();
            }
//            t = aClass.newInstance();

//            Log.i("Exception", "e=" + e.toString());
        }

        return t;
    }


//    private Type mType;
//    private Class<T> clazz;
//
//    public OkGoUtil() {
//    }
//
//    public OkGoUtil(Type type) {
//        mType = type;
//    }
//
//    public OkGoUtil(Class<T> clazz) {
//        this.clazz = clazz;
//    }
//
//    @Override
//    public T convertResponse(Response response) throws Throwable {
//
//        ResponseBody body = response.body();
//        if (body == null) {
//            return null;
//        }
//        T data = null;
//        Gson gson = new Gson();
//        String str = response.body().string();
//        if (mType != null) {
//            data = gson.fromJson(str, mType);
//        }
//        if (clazz != null) {
//            data = gson.fromJson(str, clazz);
//            //可以将错误信息在onError中获取到
//            //https://github.com/jeasonlzy/okhttp-OkGo/wiki/Callback#callback%E4%BB%8B%E7%BB%8D
//        }
//        return data;
//    }

}
