package top.octopusyan.http.callback;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import top.octopusyan.http.EasyUtils;
import top.octopusyan.http.HttpConfig;
import top.octopusyan.http.HttpLog;
import top.octopusyan.http.model.CallProxy;

import java.io.IOException;
import java.net.SocketTimeoutException;

/**
 * @author : octopus yan
 * @email : octopus_yan@foxmail.com
 * @description : 接口回调基类
 * @create : 2022-4-1 15:42
 */
public abstract class BaseCallback implements Callback {

    /** 请求任务对象 */
    private final CallProxy mCall;

    /** 当前重试次数 */
    private int mRetryCount;

    public BaseCallback(CallProxy call) {
        mCall = call;
    }

    protected CallProxy getCall() {
        return mCall;
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) {
        try {
            // 收到响应
            onResponse(response);
        } catch (Exception e) {
            // 回调失败
            onFailure(e);
        } finally {
            // 关闭响应
            response.close();
        }
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        // 服务器请求超时重试
        if (e instanceof SocketTimeoutException && mRetryCount < HttpConfig.getInstance().getRetryCount()) {
            // 设置延迟 N 秒后重试该请求
            EasyUtils.postDelayed(() -> {
                mRetryCount++;
                Call newCall = call.clone();
                mCall.setCall(newCall);
                newCall.enqueue(BaseCallback.this);
                HttpLog.print("请求超时，正在延迟重试，重试次数：" + mRetryCount + "/" + HttpConfig.getInstance().getRetryCount());

            }, HttpConfig.getInstance().getRetryTime());

            return;
        }
        onFailure(e);
    }

    protected abstract void onResponse(Response response) throws Exception;

    protected abstract void onFailure(Exception e);
}
