package com.its.vds.ui;

import javax.swing.*;
import java.io.IOException;
import java.io.OutputStream;

public class JTextAreaOutputStream extends OutputStream {

    private final JTextArea logArea;
    public static boolean isLoggingPause = false;
    private final StringBuilder sb = new StringBuilder();

    public JTextAreaOutputStream(JTextArea logArea) {
        if (logArea == null)
            throw new IllegalArgumentException ("Destination is null...");
        this.logArea = logArea;
    }

    @Override
    public void write(byte[] buffer, int offset, int length) throws IOException
    {
        if (isLoggingPause) {
            return;
        }
        final String text = new String(buffer, offset, length);
        SwingUtilities.invokeLater(new Runnable ()
        {
            @Override
            public void run()
            {
                synchronized (logArea) {
                    if (logArea.getLineCount() > 2000) {
                        logArea.setText(null);
                    }
                    logArea.append(text);
                    logArea.setCaretPosition(logArea.getDocument().getLength());
                }
            }
        });
    }

    @Override
    public void write(int b) throws IOException {
        if (isLoggingPause) {
            sb.setLength(0);
            return;
        }
        if (b == '\n') {
            final String text = sb.toString() + "\n";
            SwingUtilities.invokeLater(new Runnable ()
            {
                @Override
                public void run()
                {
                    synchronized (logArea) {
                        if (logArea.getLineCount() > 2000) {
                            logArea.setText(null);
                        }
                        logArea.append(text);
                        logArea.setCaretPosition(logArea.getDocument().getLength());
                        sb.setLength(0);
                    }
                }
            });
        } else {
            sb.append(String.valueOf((char)b));
            //sb.append((char) b);
        }
    }
}
