package org.chenyang.http.client.protocol;

import org.chenyang.http.Header;
import org.chenyang.http.HttpException;
import org.chenyang.http.HttpRequest;
import org.chenyang.http.HttpRequestInterceptor;
import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.protocol.HttpContext;
import org.chenyang.http.util.Args;
import java.io.IOException;
import java.util.Collection;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL
)
public class RequestDefaultHeaders implements HttpRequestInterceptor {
   private final Collection<? extends Header> defaultHeaders;

   public RequestDefaultHeaders(Collection<? extends Header> defaultHeaders) {
      this.defaultHeaders = defaultHeaders;
   }

   public RequestDefaultHeaders() {
      this((Collection)null);
   }

   public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
      Args.notNull(request, "HTTP request");
      String method = request.getRequestLine().getMethod();
      if (!method.equalsIgnoreCase("CONNECT")) {
         Collection<? extends Header> defHeaders = (Collection)request.getParams().getParameter("http.default-headers");
         if (defHeaders == null) {
            defHeaders = this.defaultHeaders;
         }

         if (defHeaders != null) {
            for(Header defHeader : defHeaders) {
               request.addHeader(defHeader);
            }
         }

      }
   }
}
