package com.wisewoods.base.net;

import com.blankj.utilcode.util.LogUtils;
import com.wisewoods.base.app.UserManager;
import com.wisewoods.base.bean.Results;
import com.wisewoods.base.utils.$;

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

public abstract class JCallback<T> implements Callback<T> {

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        T body = response.body();
        if (body instanceof Results) {
            Results results = (Results) body;
            if (results.isSuccess()) {
                onS(response, body);
            } else {
                invalidToken(results);
                onFailure(call, new LogicException(results.code, results.msg));
            }
        } else {
            if (response.errorBody() != null) {
                onFailure(call, new LogicException(789, "服务器错误"));
            } else {
                onS(response, body);
            }
        }
        onFinish();
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        NetWorkCodeException.ResponseThrowable responseThrowable = NetWorkCodeException.getResponseThrowable(t);
        $.toast(responseThrowable.message);
        LogUtils.e("错误:" + t.getMessage());
        onFinish();
    }

    public void onFinish() {
    }

    public void invalidToken(Results results) {
        if (results.code == 401) {
            UserManager.logout();
        }
    }

    ;


    public abstract void onS(Response<T> response, T t);
}
