package org.chenyang.http.protocol;

import org.chenyang.http.HttpException;
import org.chenyang.http.HttpRequest;
import org.chenyang.http.HttpRequestInterceptor;
import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.params.HttpParams;
import org.chenyang.http.util.Args;
import java.io.IOException;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE
)
public class RequestUserAgent implements HttpRequestInterceptor {
   private final String userAgent;

   public RequestUserAgent(String userAgent) {
      this.userAgent = userAgent;
   }

   public RequestUserAgent() {
      this(null);
   }

   public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
      Args.notNull(request, "HTTP request");
      if (!request.containsHeader("User-Agent")) {
         String s = null;
         HttpParams params = request.getParams();
         if (params != null) {
            s = (String)params.getParameter("http.useragent");
         }

         if (s == null) {
            s = this.userAgent;
         }

         if (s != null) {
            request.addHeader("User-Agent", s);
         }
      }

   }
}
