package org.chenyang.http.impl.io;

import org.chenyang.http.ConnectionClosedException;
import org.chenyang.http.HttpException;
import org.chenyang.http.HttpRequest;
import org.chenyang.http.HttpRequestFactory;
import org.chenyang.http.ParseException;
import org.chenyang.http.RequestLine;
import org.chenyang.http.config.MessageConstraints;
import org.chenyang.http.impl.DefaultHttpRequestFactory;
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.util.Args;
import org.chenyang.http.util.CharArrayBuffer;
import java.io.IOException;

public class DefaultHttpRequestParser extends AbstractMessageParser<HttpRequest> {
   private final HttpRequestFactory requestFactory;
   private final CharArrayBuffer lineBuf;

   /** @deprecated */
   @Deprecated
   public DefaultHttpRequestParser(SessionInputBuffer buffer, LineParser lineParser, HttpRequestFactory requestFactory, HttpParams params) {
      super(buffer, lineParser, params);
      this.requestFactory = (HttpRequestFactory)Args.notNull(requestFactory, "Request factory");
      this.lineBuf = new CharArrayBuffer(128);
   }

   public DefaultHttpRequestParser(SessionInputBuffer buffer, LineParser lineParser, HttpRequestFactory requestFactory, MessageConstraints constraints) {
      super(buffer, lineParser, constraints);
      this.requestFactory = (HttpRequestFactory)(requestFactory != null ? requestFactory : DefaultHttpRequestFactory.INSTANCE);
      this.lineBuf = new CharArrayBuffer(128);
   }

   public DefaultHttpRequestParser(SessionInputBuffer buffer, MessageConstraints constraints) {
      this(buffer, (LineParser)null, (HttpRequestFactory)null, (MessageConstraints)constraints);
   }

   public DefaultHttpRequestParser(SessionInputBuffer buffer) {
      this(buffer, (LineParser)null, (HttpRequestFactory)null, (MessageConstraints)MessageConstraints.DEFAULT);
   }

   protected HttpRequest parseHead(SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException {
      this.lineBuf.clear();
      int readLen = sessionBuffer.readLine(this.lineBuf);
      if (readLen == -1) {
         throw new ConnectionClosedException("Client closed connection");
      } else {
         ParserCursor cursor = new ParserCursor(0, this.lineBuf.length());
         RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor);
         return this.requestFactory.newHttpRequest(requestline);
      }
   }
}
