package nl.client;

import java.io.IOException;

import nl.hippo.client.api.caching.Cache;
import nl.hippo.client.api.caching.CachedResponse;
import nl.hippo.client.api.event.EventAwareManager;
import nl.hippo.client.api.service.CachingService;
import nl.hippo.client.caching.service.CachingServiceImpl;
import nl.hippo.client.webdav.WebdavResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Implementation of CachingService which only overrides the store(), to add another decision.
 * 
 * @author gvanderPloeg
 *
 */
public class NoErrorResponseCachingServiceImpl extends CachingServiceImpl implements CachingService {

   private static Log log = LogFactory.getLog(NoErrorResponseCachingServiceImpl.class);

   public NoErrorResponseCachingServiceImpl(Cache cache, EventAwareManager eventAwareManager, String namespace) {
      super(cache, eventAwareManager, namespace);
   }

   public NoErrorResponseCachingServiceImpl(Cache cache) {
      super(cache);
   }

   /**
    * {@inheritDoc}
    * <br />
    * This implementation: call super's store(), but only if response is not a HTTP 4xx or 5xx response.
    *  
    */
   @Override
   public void store(Object key, Object obj) throws IOException {
      if (obj instanceof CachedResponse) {
         CachedResponse cachedResponse = (CachedResponse) obj;
         if (cachedResponse.getResponse() instanceof WebdavResponse) {
            WebdavResponse response = (WebdavResponse) cachedResponse.getResponse();
            if (response.getResponseCode() >= 400) {
               // will not cache error results. See RFC 2616 for definition of response codes.
               if (log.isDebugEnabled()) {
                  log.debug("Will not cache response as HTTP response code >= 400. Response code: " + response.getResponseCode());
               }
               return;
            } else {
               if (log.isDebugEnabled()) {
                  log.debug("Will cache response as HTTP response code not >= 400. Response code: " + response.getResponseCode());
               }
            }
         }
      }
      super.store(key, obj);
   }
}

