package com.xunao.effectdemo.net;

import android.text.TextUtils;
import android.util.Log;

import com.xunao.effectdemo.utils.StringUtil;
import com.zhy.http.okhttp.callback.Callback;

import java.io.ByteArrayInputStream;

import okhttp3.Call;
import okhttp3.Response;

public abstract class CSMHttpCallback extends Callback<String> {

    private final static String TAG = CSMHttpCallback.class.getName();

    protected abstract void onSuccess(String jsonStr);

    protected abstract void onFail(String msg);

    @Override
    public boolean validateReponse(Response response, int id) {
        return true;
    }

    @Override
    public String parseNetworkResponse(Response response, int id) throws Exception {
        String url = response.request().url().toString();
        String responseStr = StringUtil.inputStream2String(new ByteArrayInputStream(response.body().bytes()), "utf-8");

        switch (response.code()) {
            case 200:
                return responseStr;
            case 401:
                break;
            default:
        }
        return "";
    }

    @Override
    public void onError(Call call, Exception exception, int id) {
        exception.printStackTrace();
    }

    @Override
    public void onResponse(String response, int id) {
        Log.i(TAG, "response==>" + response);
        if (!TextUtils.isEmpty(response)) {
            if (response.contains("retCode")){
                BaseBean baseBean = BaseBean.parse(response);
                if (baseBean.getRetCode().equals("0")) {
                    onSuccess(response);
                }else if(baseBean.getRetCode().equals("1007")||baseBean.getRetCode().equals("1005")){
                    onFail("1007");

                } else {
                    onFail("请求报错");
                }
            }else{
                onSuccess(response);
            }
        } else {
//            onFail(BmonsterApplication.resources().getString(R.string.net_error));
        }
    }
}
