package Tools;

import java.io.*;

/**
 * Insert this filter among your <code>InputStream</code>s to have the
 * data passing through the stream logged with the {@link Log} tool.
 *
 * @classConcise true
 */
public class SnoopyIn extends FilterInputStream {
	InputStream is;
	Log log;

	public SnoopyIn(InputStream in, Log log) {
		super(in);
		this.log = log;
	}

	public int read(byte b[])
	throws IOException {
		preread();
		int rc = in.read(b);
		log.log("snoop", ": snoop <= ["+b.length+": "+b[0]+"...] = "+rc+stream());
		return rc;
	}

	public int read(byte b[], int off, int len)
	throws IOException {
		preread();
		int rc = in.read(b, off, len);
		log.log("snoop", ": snoop <= ["+len+"@"+off+": "+b[0]+"...] = "+rc+stream());
		return rc;
	}

	public int read()
	throws IOException {
		preread();
		int rc = in.read();
		log.log("snoop", ": snoop <= 1 = "+rc+stream());
		return rc;
	}

	public String stream() {
		return "  <"+in.toString();
	}

	void preread() {
		// new Throwable(" --preread:").printStackTrace();
	}
}
