package org.chenyang.http.impl.conn;

import org.chenyang.commons.logging.Log;
import org.chenyang.commons.logging.LogFactory;
import org.chenyang.http.HttpException;
import org.chenyang.http.HttpMessage;
import org.chenyang.http.HttpResponseFactory;
import org.chenyang.http.NoHttpResponseException;
import org.chenyang.http.ProtocolException;
import org.chenyang.http.StatusLine;
import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.impl.io.AbstractMessageParser;
import org.chenyang.http.io.SessionInputBuffer;
import org.chenyang.http.message.LineParser;
import org.chenyang.http.message.ParserCursor;
import org.chenyang.http.params.HttpParams;
import org.chenyang.http.protocol.HttpContext;
import org.chenyang.http.util.Args;
import org.chenyang.http.util.CharArrayBuffer;
import java.io.IOException;

/** @deprecated */
@Deprecated
@Contract(
   threading = ThreadingBehavior.SAFE_CONDITIONAL
)
public class DefaultResponseParser extends AbstractMessageParser<HttpMessage> {
   private final Log log = LogFactory.getLog(this.getClass());
   private final HttpResponseFactory responseFactory;
   private final CharArrayBuffer lineBuf;
   private final int maxGarbageLines;

   public DefaultResponseParser(SessionInputBuffer buffer, LineParser parser, HttpResponseFactory responseFactory, HttpParams params) {
      super(buffer, parser, params);
      Args.notNull(responseFactory, "Response factory");
      this.responseFactory = responseFactory;
      this.lineBuf = new CharArrayBuffer(128);
      this.maxGarbageLines = this.getMaxGarbageLines(params);
   }

   protected int getMaxGarbageLines(HttpParams params) {
      return params.getIntParameter("http.connection.max-status-line-garbage", Integer.MAX_VALUE);
   }

   protected HttpMessage parseHead(SessionInputBuffer sessionBuffer) throws IOException, HttpException {
      int count = 0;
      ParserCursor cursor = null;

      while(true) {
         this.lineBuf.clear();
         int i = sessionBuffer.readLine(this.lineBuf);
         if (i == -1 && count == 0) {
            throw new NoHttpResponseException("The target server failed to respond");
         }

         cursor = new ParserCursor(0, this.lineBuf.length());
         if (this.lineParser.hasProtocolVersion(this.lineBuf, cursor)) {
            StatusLine statusline = this.lineParser.parseStatusLine(this.lineBuf, cursor);
            return this.responseFactory.newHttpResponse(statusline, (HttpContext)null);
         }

         if (i == -1 || count >= this.maxGarbageLines) {
            throw new ProtocolException("The server failed to respond with a valid HTTP response");
         }

         if (this.log.isDebugEnabled()) {
            this.log.debug("Garbage in response: " + this.lineBuf.toString());
         }

         ++count;
      }
   }
}
