package org.chenyang.http.impl;

import org.chenyang.http.HttpResponse;
import org.chenyang.http.HttpResponseFactory;
import org.chenyang.http.ProtocolVersion;
import org.chenyang.http.ReasonPhraseCatalog;
import org.chenyang.http.StatusLine;
import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.message.BasicHttpResponse;
import org.chenyang.http.message.BasicStatusLine;
import org.chenyang.http.protocol.HttpContext;
import org.chenyang.http.util.Args;
import java.util.Locale;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL
)
public class DefaultHttpResponseFactory implements HttpResponseFactory {
   public static final DefaultHttpResponseFactory INSTANCE = new DefaultHttpResponseFactory();
   protected final ReasonPhraseCatalog reasonCatalog;

   public DefaultHttpResponseFactory(ReasonPhraseCatalog catalog) {
      this.reasonCatalog = (ReasonPhraseCatalog)Args.notNull(catalog, "Reason phrase catalog");
   }

   public DefaultHttpResponseFactory() {
      this(EnglishReasonPhraseCatalog.INSTANCE);
   }

   public HttpResponse newHttpResponse(ProtocolVersion ver, int status, HttpContext context) {
      Args.notNull(ver, "HTTP version");
      Locale loc = this.determineLocale(context);
      String reason = this.reasonCatalog.getReason(status, loc);
      StatusLine statusline = new BasicStatusLine(ver, status, reason);
      return new BasicHttpResponse(statusline, this.reasonCatalog, loc);
   }

   public HttpResponse newHttpResponse(StatusLine statusline, HttpContext context) {
      Args.notNull(statusline, "Status line");
      return new BasicHttpResponse(statusline, this.reasonCatalog, this.determineLocale(context));
   }

   protected Locale determineLocale(HttpContext context) {
      return Locale.getDefault();
   }
}
