package org.chenyang.http.impl.conn;

import org.chenyang.http.HttpException;
import org.chenyang.http.HttpHost;
import org.chenyang.http.HttpRequest;
import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.conn.params.ConnRouteParams;
import org.chenyang.http.conn.routing.HttpRoute;
import org.chenyang.http.conn.routing.HttpRoutePlanner;
import org.chenyang.http.conn.scheme.Scheme;
import org.chenyang.http.conn.scheme.SchemeRegistry;
import org.chenyang.http.protocol.HttpContext;
import org.chenyang.http.util.Args;
import org.chenyang.http.util.Asserts;
import java.net.InetAddress;

/** @deprecated */
@Deprecated
@Contract(
   threading = ThreadingBehavior.SAFE
)
public class DefaultHttpRoutePlanner implements HttpRoutePlanner {
   protected final SchemeRegistry schemeRegistry;

   public DefaultHttpRoutePlanner(SchemeRegistry schreg) {
      Args.notNull(schreg, "Scheme registry");
      this.schemeRegistry = schreg;
   }

   public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
      Args.notNull(request, "HTTP request");
      HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams());
      if (route != null) {
         return route;
      } else {
         Asserts.notNull(target, "Target host");
         InetAddress local = ConnRouteParams.getLocalAddress(request.getParams());
         HttpHost proxy = ConnRouteParams.getDefaultProxy(request.getParams());

         Scheme schm;
         try {
            schm = this.schemeRegistry.getScheme(target.getSchemeName());
         } catch (IllegalStateException ex) {
            throw new HttpException(ex.getMessage());
         }

         boolean secure = schm.isLayered();
         if (proxy == null) {
            route = new HttpRoute(target, local, secure);
         } else {
            route = new HttpRoute(target, local, proxy, secure);
         }

         return route;
      }
   }
}
