package org.chenyang.http.client.protocol;

import org.chenyang.commons.logging.Log;
import org.chenyang.commons.logging.LogFactory;
import org.chenyang.http.HttpException;
import org.chenyang.http.HttpHost;
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.auth.AuthProtocolState;
import org.chenyang.http.auth.AuthScheme;
import org.chenyang.http.auth.AuthScope;
import org.chenyang.http.auth.AuthState;
import org.chenyang.http.auth.Credentials;
import org.chenyang.http.client.AuthCache;
import org.chenyang.http.client.CredentialsProvider;
import org.chenyang.http.conn.routing.RouteInfo;
import org.chenyang.http.protocol.HttpContext;
import org.chenyang.http.util.Args;
import java.io.IOException;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE
)
public class RequestAuthCache implements HttpRequestInterceptor {
   private final Log log = LogFactory.getLog(this.getClass());

   public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
      Args.notNull(request, "HTTP request");
      Args.notNull(context, "HTTP context");
      HttpClientContext clientContext = HttpClientContext.adapt(context);
      AuthCache authCache = clientContext.getAuthCache();
      if (authCache == null) {
         this.log.debug("Auth cache not set in the context");
      } else {
         CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
         if (credsProvider == null) {
            this.log.debug("Credentials provider not set in the context");
         } else {
            RouteInfo route = clientContext.getHttpRoute();
            if (route == null) {
               this.log.debug("Route info not set in the context");
            } else {
               HttpHost target = clientContext.getTargetHost();
               if (target == null) {
                  this.log.debug("Target host not set in the context");
               } else {
                  if (target.getPort() < 0) {
                     target = new HttpHost(target.getHostName(), route.getTargetHost().getPort(), target.getSchemeName());
                  }

                  AuthState targetState = clientContext.getTargetAuthState();
                  if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) {
                     AuthScheme authScheme = authCache.get(target);
                     if (authScheme != null) {
                        this.doPreemptiveAuth(target, authScheme, targetState, credsProvider);
                     }
                  }

                  HttpHost proxy = route.getProxyHost();
                  AuthState proxyState = clientContext.getProxyAuthState();
                  if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) {
                     AuthScheme authScheme = authCache.get(proxy);
                     if (authScheme != null) {
                        this.doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
                     }
                  }

               }
            }
         }
      }
   }

   private void doPreemptiveAuth(HttpHost host, AuthScheme authScheme, AuthState authState, CredentialsProvider credsProvider) {
      String schemeName = authScheme.getSchemeName();
      if (this.log.isDebugEnabled()) {
         this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
      }

      AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName);
      Credentials creds = credsProvider.getCredentials(authScope);
      if (creds != null) {
         authState.update(authScheme, creds);
      } else {
         this.log.debug("No credentials for preemptive authentication");
      }

   }
}
