package org.chenyang.http.protocol;

import org.chenyang.http.Header;
import org.chenyang.http.HttpEntity;
import org.chenyang.http.HttpException;
import org.chenyang.http.HttpRequest;
import org.chenyang.http.HttpResponse;
import org.chenyang.http.HttpResponseInterceptor;
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 ResponseConnControl implements HttpResponseInterceptor {
   public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
      Args.notNull(response, "HTTP response");
      HttpCoreContext corecontext = HttpCoreContext.adapt(context);
      int status = response.getStatusLine().getStatusCode();
      if (status != 400 && status != 408 && status != 411 && status != 413 && status != 414 && status != 503 && status != 501) {
         Header explicit = response.getFirstHeader("Connection");
         if (explicit == null || !"Close".equalsIgnoreCase(explicit.getValue())) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
               ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
               if (entity.getContentLength() < 0L && (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) {
                  response.setHeader("Connection", "Close");
                  return;
               }
            }

            HttpRequest request = corecontext.getRequest();
            if (request != null) {
               Header header = request.getFirstHeader("Connection");
               if (header != null) {
                  response.setHeader("Connection", header.getValue());
               } else if (request.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) {
                  response.setHeader("Connection", "Close");
               }
            }

         }
      } else {
         response.setHeader("Connection", "Close");
      }
   }
}
