package com.its.pis.ui;

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

public class JTextAreaOutputStream extends OutputStream {

    private final JTextArea logArea;
    public static boolean isLoggingPause = false;

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

    public synchronized void logWrite(String text) {
        Runnable  runnable = new Runnable() {
            public void run() {
                logArea.append(text);
                if (logArea.getDocument().getLength() >
                        50000) {
                    try {
                        logArea.getDocument().remove(0, 5000);
                    } catch (BadLocationException e) {
                        //log.error("Can't clean log", e);
                    }
                }
                logArea.setCaretPosition(logArea.getDocument().getLength());
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    @Override
    public void write(byte[] buffer, int offset, int length) throws IOException
    {
        if (isLoggingPause) {
            return;
        }

        final String text = new String(buffer, offset, length);
        //logWrite(text);
        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 {
        write (new byte [] {(byte)b}, 0, 1);
    }
}
