package com.qmth.boot.core.retrofit.interceptor;

import com.qmth.boot.core.retrofit.config.RetryProperties;
import okhttp3.Interceptor;
import okhttp3.Response;

import java.io.IOException;

public class RetryInterceptor implements Interceptor {

    private RetryProperties retryProperties;

    public RetryInterceptor(RetryProperties retryProperties) {
        this.retryProperties = retryProperties;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        int count = 0;
        Response response = chain.proceed(chain.request());
        while (needRetry(response, count)) {
            response.close();
            sleep();
            response = chain.proceed(chain.request());
            count++;
        }
        return response;
    }

    private boolean needRetry(Response response, int count) {
        if (response.isSuccessful() || !retryProperties.getStatusCode().contains(response.code())) {
            return false;
        }
        return count < retryProperties.getCount();
    }

    private void sleep() {
        if (retryProperties.getInterval().toMillis() > 0) {
            try {
                Thread.sleep(retryProperties.getInterval().toMillis());
            } catch (Exception e) {
                throw new RuntimeException("Retrofit retry sleep interupted", e);
            }
        }
    }

}
