package org.chenyang.http.impl.client;

import org.chenyang.http.Header;
import org.chenyang.http.HttpRequest;
import org.chenyang.http.HttpResponse;
import org.chenyang.http.TokenIterator;
import org.chenyang.http.impl.DefaultConnectionReuseStrategy;
import org.chenyang.http.message.BasicHeaderIterator;
import org.chenyang.http.message.BasicTokenIterator;
import org.chenyang.http.protocol.HttpContext;

public class DefaultClientConnectionReuseStrategy extends DefaultConnectionReuseStrategy {
   public static final DefaultClientConnectionReuseStrategy INSTANCE = new DefaultClientConnectionReuseStrategy();

   public boolean keepAlive(HttpResponse response, HttpContext context) {
      HttpRequest request = (HttpRequest)context.getAttribute("http.request");
      if (request != null) {
         Header[] connHeaders = request.getHeaders("Connection");
         if (connHeaders.length != 0) {
            TokenIterator ti = new BasicTokenIterator(new BasicHeaderIterator(connHeaders, null));

            while(ti.hasNext()) {
               String token = ti.nextToken();
               if ("Close".equalsIgnoreCase(token)) {
                  return false;
               }
            }
         }
      }

      return super.keepAlive(response, context);
   }
}
