package gnomenWald17;

// Acknowledgments:
// https://tips4java.wordpress.com/2008/11/08/message-console/
// http://www.camick.com/java/source/MessageConsole.java
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;

public class GUIText {
	private JTextPane text;
	private Document document;

	public GUIText(JTextPane t){
		this.text = t;
		this.document = text.getDocument();
		text.setEditable( false );
	}

	public void redirectOut(){
		ConsoleOutputStream cos = new ConsoleOutputStream();
		System.setOut(new PrintStream (cos, true));
		System.setErr(new PrintStream (cos, true));
	}

	public class ConsoleOutputStream extends ByteArrayOutputStream{
		private final String EOL = System.getProperty("line.separator");
		private SimpleAttributeSet attributes;
		//private PrintStream printStream;
		private StringBuffer buffer = new StringBuffer(80);
		private boolean isFirstLine;

		public ConsoleOutputStream() {
			isFirstLine = true;
		}

		public void flush(){
			String message = toString();
			if (message.length() == 0) return;
			handleAppend(message);
			reset();
		}

		private void handleAppend (String message){
			if (document.getLength()==0)
				buffer.setLength(0);
			if (EOL.equals(message))
				buffer.append(message);
			else{
				buffer.append(message);
				clearBuffer();
			}
		}

		private void clearBuffer(){
			if (isFirstLine && document.getLength() != 0)
				buffer.insert(0, "\n");
			isFirstLine = false;
			String line = buffer.toString();
			try{
				int offset = document.getLength();
				document.insertString(offset,line,attributes);
				text.setCaretPosition(document.getLength());
			}catch(BadLocationException ble){
			}
			buffer.setLength(0);
		}
	}
}