package org.chenyang.http.impl.entity;

import org.chenyang.http.HttpEntity;
import org.chenyang.http.HttpException;
import org.chenyang.http.HttpMessage;
import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.entity.ContentLengthStrategy;
import org.chenyang.http.impl.io.ChunkedOutputStream;
import org.chenyang.http.impl.io.ContentLengthOutputStream;
import org.chenyang.http.impl.io.IdentityOutputStream;
import org.chenyang.http.io.SessionOutputBuffer;
import org.chenyang.http.util.Args;
import java.io.IOException;
import java.io.OutputStream;

/** @deprecated */
@Deprecated
@Contract(
   threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL
)
public class EntitySerializer {
   private final ContentLengthStrategy lenStrategy;

   public EntitySerializer(ContentLengthStrategy lenStrategy) {
      this.lenStrategy = (ContentLengthStrategy)Args.notNull(lenStrategy, "Content length strategy");
   }

   protected OutputStream doSerialize(SessionOutputBuffer outbuffer, HttpMessage message) throws HttpException, IOException {
      long len = this.lenStrategy.determineLength(message);
      if (len == -2L) {
         return new ChunkedOutputStream(outbuffer);
      } else {
         return (OutputStream)(len == -1L ? new IdentityOutputStream(outbuffer) : new ContentLengthOutputStream(outbuffer, len));
      }
   }

   public void serialize(SessionOutputBuffer outbuffer, HttpMessage message, HttpEntity entity) throws HttpException, IOException {
      Args.notNull(outbuffer, "Session output buffer");
      Args.notNull(message, "HTTP message");
      Args.notNull(entity, "HTTP entity");
      OutputStream outStream = this.doSerialize(outbuffer, message);
      entity.writeTo(outStream);
      outStream.close();
   }
}
