package com.zhimai.websocket.http;

import java.io.IOException;
import java.net.UnknownHostException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class RetryIntercepter implements Interceptor {
    public int maxRetryCount;
    private int count = 0;
    public RetryIntercepter(int maxRetryCount) {
        this.maxRetryCount = maxRetryCount;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        return retry(chain);
    }

    public Response retry(Chain chain) throws IOException {
        Response response = null;
        Request request = chain.request();
        try {
            response = chain.proceed(request);
            while (!response.isSuccessful() && count < maxRetryCount) {
                count++;
                response = retry(chain);
            }
        }
        catch( UnknownHostException ignored){
            throw ignored;
        }
        catch (Exception e){
            while (count < maxRetryCount){
                count++;
                response = retry(chain);
            }
        }
        if (response==null){
           throw new IOException("");
        }
        return response;
    }
}
