package com.daya.live_teaching.api.retrofit;


import com.cooleshow.base.utils.LogUtils;
import com.daya.live_teaching.common.ErrorCode;
import com.daya.live_teaching.common.ResultCallback;
import com.daya.live_teaching.model.Result;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CallBackWrapper<R> implements Callback<Result<R>> {
    private ResultCallback<R> mCallBack;

    public CallBackWrapper(ResultCallback<R> callBack) {
        mCallBack = callBack;
    }

    @Override
    public void onResponse(Call<Result<R>> call, Response<Result<R>> response) {
        Result<R> body = response.body();
        if (body != null) {
            int errCode = body.getErrCode();

            if (errCode == 0 || body.getCode() == 200) {
                mCallBack.onSuccess(body.getDataResult());
            } else {
                LogUtils.e("url:" + call.request().url().toString()
                        + " ,errorMsg:" + body.getErrMsg() + ", errorDetail:" + body.getErrDetail());
                mCallBack.onFail(errCode, body.getErrMsg());
            }
        } else {
            LogUtils.e("url:" + call.request().url().toString() + ", no response body");
            mCallBack.onFail(ErrorCode.API_ERR_OTHER.getCode(), null);
        }
    }

    @Override
    public void onFailure(Call<Result<R>> call, Throwable t) {
        LogUtils.e(call.request().url().toString() + " - " + (t != null ? t.getMessage() : ""));
        mCallBack.onFail(ErrorCode.NETWORK_ERROR.getCode(), null);
    }
}
