package jp.cssj.cti.helpers;

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

/**
 * @author <a href="mailto:miyabe at gnn.co.jp">MIYABE Tatsuhiko </a>
 * @version $Id: RequestProducerInputStream.java,v 1.1 2005/03/26 10:22:30
 *          harumanx Exp $
 */
public class RequestProducerInputStream extends InputStream implements
		Progressive {
	private final RequestProducer producer;

	private final byte[] buff = new byte[1];

	private int progress = 0;

	public RequestProducerInputStream(RequestProducer producer) {
		this.producer = producer;
	}

	public long getProgress() {
		return this.progress;
	}

	public int read() throws IOException {
		if (this.producer.getType() != RequestProducer.DATA) {
			return -1;
		}
		int read = this.producer.read(this.buff, 0, 1);
		if (read == 1) {
			++this.progress;
			return this.buff[0];
		}
		this.producer.next();
		if (this.producer.getType() == RequestProducer.DATA) {
			return this.read();
		}
		return -1;

	}

	public int read(byte[] b, int off, int len) throws IOException {
		if (this.producer.getType() != RequestProducer.DATA) {
			return -1;
		}
		int read = this.producer.read(b, off, len);
		if (read != -1) {
			this.progress += read;
			return read;
		}
		this.producer.next();
		if (this.producer.getType() == RequestProducer.DATA) {
			return this.read(b, off, len);
		}
		return -1;
	}

	public int read(byte[] b) throws IOException {
		if (this.producer.getType() != RequestProducer.DATA) {
			return -1;
		}
		int read = this.producer.read(b, 0, b.length);
		if (read != -1) {
			this.progress += read;
			return read;
		}
		this.producer.next();
		if (this.producer.getType() == RequestProducer.DATA) {
			return this.read(b, 0, b.length);
		}
		return -1;
	}
}