package org.chenyang.http.client.protocol;

import org.chenyang.commons.logging.Log;
import org.chenyang.commons.logging.LogFactory;
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.conn.routing.RouteInfo;
import org.chenyang.http.protocol.HttpContext;
import org.chenyang.http.util.Args;
import java.io.IOException;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE
)
public class RequestClientConnControl implements HttpRequestInterceptor {
   private final Log log = LogFactory.getLog(this.getClass());
   private static final String PROXY_CONN_DIRECTIVE = "Proxy-Connection";

   public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
      Args.notNull(request, "HTTP request");
      String method = request.getRequestLine().getMethod();
      if (method.equalsIgnoreCase("CONNECT")) {
         request.setHeader("Proxy-Connection", "Keep-Alive");
      } else {
         HttpClientContext clientContext = HttpClientContext.adapt(context);
         RouteInfo route = clientContext.getHttpRoute();
         if (route == null) {
            this.log.debug("Connection route not set in the context");
         } else {
            if ((route.getHopCount() == 1 || route.isTunnelled()) && !request.containsHeader("Connection")) {
               request.addHeader("Connection", "Keep-Alive");
            }

            if (route.getHopCount() == 2 && !route.isTunnelled() && !request.containsHeader("Proxy-Connection")) {
               request.addHeader("Proxy-Connection", "Keep-Alive");
            }

         }
      }
   }
}
