package org.chenyang.http.impl.client;

import org.chenyang.http.HttpResponse;
import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.client.ServiceUnavailableRetryStrategy;
import org.chenyang.http.protocol.HttpContext;
import org.chenyang.http.util.Args;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE
)
public class DefaultServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy {
   private final int maxRetries;
   private final long retryInterval;

   public DefaultServiceUnavailableRetryStrategy(int maxRetries, int retryInterval) {
      Args.positive(maxRetries, "Max retries");
      Args.positive(retryInterval, "Retry interval");
      this.maxRetries = maxRetries;
      this.retryInterval = (long)retryInterval;
   }

   public DefaultServiceUnavailableRetryStrategy() {
      this(1, 1000);
   }

   public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
      return executionCount <= this.maxRetries && response.getStatusLine().getStatusCode() == 503;
   }

   public long getRetryInterval() {
      return this.retryInterval;
   }
}
