//  This software code is made available "AS IS" without warranties of any
//  kind.  You may copy, display, modify and redistribute the software
//  code either by itself or as incorporated into your code; provided that
//  you do not remove any proprietary notices.  Your use of this software
//  code is at your own risk and you waive any claim against Amazon
//  Digital Services, Inc. or its affiliates with respect to your use of
//  this software code. (c) 2006 Amazon Digital Services, Inc. or its
//  affiliates.

package net.noderunner.amazon.s3;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;

/**
 * Returned by the {@link Connection#get(Bucket, String)} methods.
 */
public class GetResponse extends Response {

	private S3Object object;

	GetResponse(HttpMethod method) throws IOException {
		super(method);
		if (getResponseCode() < 400) {
			long len = ((HttpMethodBase)method).getResponseContentLength();
			byte[] body = toByteArray(method.getResponseBodyAsStream(), len);
			object = new S3Object(body, getHeaders().extractMetadata());
		}
	}

	/**
	 * Read the input stream and dump it all into a big byte array
	 */
	private static byte[] toByteArray(InputStream stream, long len) throws IOException {
		final int chunkSize = 4 * 1024;
		byte[] buf = new byte[chunkSize];
		ByteArrayOutputStream baos;
		if (len != -1) {
			baos = new ByteArrayOutputStream((int)len);
		} else {
			baos = new ByteArrayOutputStream(chunkSize);
		}

		int count;
		while ((count = stream.read(buf)) != -1)
			baos.write(buf, 0, count);

		return baos.toByteArray();
	}

	/**
	 * Returns the S3 object.
	 */
	public S3Object getObject() {
		return object;
	}
	
	/**
	 * Returns a debug string.
	 */
	@Override
	public String toString() {
		return super.toString() + " object=" + object;
	}
}
