package org.chenyang.http.protocol;

import org.chenyang.http.HttpEntity;
import org.chenyang.http.HttpEntityEnclosingRequest;
import org.chenyang.http.HttpException;
import org.chenyang.http.HttpRequest;
import org.chenyang.http.HttpRequestInterceptor;
import org.chenyang.http.HttpVersion;
import org.chenyang.http.ProtocolVersion;
import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.util.Args;
import java.io.IOException;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE
)
public class RequestExpectContinue implements HttpRequestInterceptor {
   private final boolean activeByDefault;

   /** @deprecated */
   @Deprecated
   public RequestExpectContinue() {
      this(false);
   }

   public RequestExpectContinue(boolean activeByDefault) {
      this.activeByDefault = activeByDefault;
   }

   public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
      Args.notNull(request, "HTTP request");
      if (!request.containsHeader("Expect") && request instanceof HttpEntityEnclosingRequest) {
         ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
         HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
         if (entity != null && entity.getContentLength() != 0L && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
            boolean active = request.getParams().getBooleanParameter("http.protocol.expect-continue", this.activeByDefault);
            if (active) {
               request.addHeader("Expect", "100-continue");
            }
         }
      }

   }
}
