package ch.wlkl.shell;

import java.io.IOException;
import java.io.OutputStream;

public class OutputStream2Write extends OutputStream implements Write<String> {

		Write<String> out;
		StringBuffer buf = new StringBuffer();

		boolean bufUsed = false; 

		OutputStream2Write(Write<String> w) {
			out = w;
		}
		public void flush() {
			if (bufUsed) {
				out.write(buf.toString());
				buf.setLength(0);
				bufUsed = false;
			}
		}
		
		public void close() {
			flush();
		}

		public void write(int b) throws IOException {
			bufUsed = true;
			if (b == '\n' || b == '\r') 
				flush();
			else 
				buf.append((char) b);
		}

		public void write(byte[] b, int off, int len) throws IOException {
			int x = off;
			int end = off + len;
			while (x < end) {
				bufUsed = true;
				if (b[x] == '\n') { 
					flush();
					x ++;
				} else if (b[x] == '\r') { 
					flush();
					x += x+1<end && b[x+1] == '\n' ? 2 : 1;
				} else {
					buf.append((char) b[x]);
					x++;
				}
			}
//			len -= len <= 0 ? 0 : b[off+len-1] == '\r' ? 1 : b[off+len-1] != '\n' ? 0 : len > 1 && b[off+len-2] == '\r' ? 2 : 1;
//			prnt.println("write(bytes[], ," + len + ") " + new String(b, off, len));
		}

		public void write(String arg) {
			buf.append(arg);
			flush();
		}

		public void open(String opt) {
			close();
			if (! ("w".equals(opt) || "a".equals(opt)))
				Top.sFail("bad opt " + opt);
		}

		@SuppressWarnings("unchecked")
		public void reset(Object... args) {
			if (args.length > 0)
				out = (Write<String>) args[0];
		}


}

