package org.chenyang.http.impl.io;

import org.chenyang.http.HttpException;
import org.chenyang.http.HttpResponse;
import org.chenyang.http.HttpResponseFactory;
import org.chenyang.http.NoHttpResponseException;
import org.chenyang.http.ParseException;
import org.chenyang.http.StatusLine;
import org.chenyang.http.config.MessageConstraints;
import org.chenyang.http.impl.DefaultHttpResponseFactory;
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;

public class DefaultHttpResponseParser extends AbstractMessageParser<HttpResponse> {
   private final HttpResponseFactory responseFactory;
   private final CharArrayBuffer lineBuf;

   /** @deprecated */
   @Deprecated
   public DefaultHttpResponseParser(SessionInputBuffer buffer, LineParser lineParser, HttpResponseFactory responseFactory, HttpParams params) {
      super(buffer, lineParser, params);
      this.responseFactory = (HttpResponseFactory)Args.notNull(responseFactory, "Response factory");
      this.lineBuf = new CharArrayBuffer(128);
   }

   public DefaultHttpResponseParser(SessionInputBuffer buffer, LineParser lineParser, HttpResponseFactory responseFactory, MessageConstraints constraints) {
      super(buffer, lineParser, constraints);
      this.responseFactory = (HttpResponseFactory)(responseFactory != null ? responseFactory : DefaultHttpResponseFactory.INSTANCE);
      this.lineBuf = new CharArrayBuffer(128);
   }

   public DefaultHttpResponseParser(SessionInputBuffer buffer, MessageConstraints constraints) {
      this(buffer, (LineParser)null, (HttpResponseFactory)null, (MessageConstraints)constraints);
   }

   public DefaultHttpResponseParser(SessionInputBuffer buffer) {
      this(buffer, (LineParser)null, (HttpResponseFactory)null, (MessageConstraints)MessageConstraints.DEFAULT);
   }

   protected HttpResponse parseHead(SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException {
      this.lineBuf.clear();
      int readLen = sessionBuffer.readLine(this.lineBuf);
      if (readLen == -1) {
         throw new NoHttpResponseException("The target server failed to respond");
      } else {
         ParserCursor cursor = new ParserCursor(0, this.lineBuf.length());
         StatusLine statusline = this.lineParser.parseStatusLine(this.lineBuf, cursor);
         return this.responseFactory.newHttpResponse(statusline, (HttpContext)null);
      }
   }
}
