package org.chenyang.http.impl.entity;

import org.chenyang.http.HttpException;
import org.chenyang.http.HttpMessage;
import org.chenyang.http.ProtocolException;
import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.entity.ContentLengthStrategy;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL
)
public class DisallowIdentityContentLengthStrategy implements ContentLengthStrategy {
   public static final DisallowIdentityContentLengthStrategy INSTANCE = new DisallowIdentityContentLengthStrategy(new LaxContentLengthStrategy(0));
   private final ContentLengthStrategy contentLengthStrategy;

   public DisallowIdentityContentLengthStrategy(ContentLengthStrategy contentLengthStrategy) {
      this.contentLengthStrategy = contentLengthStrategy;
   }

   public long determineLength(HttpMessage message) throws HttpException {
      long result = this.contentLengthStrategy.determineLength(message);
      if (result == -1L) {
         throw new ProtocolException("Identity transfer encoding cannot be used");
      } else {
         return result;
      }
   }
}
