
/*
 * Copyright (C) 1999-2006 <a href="mailto:adrian.paschke@gmx.de">Adrian Paschke</a>
 * 
 * The RBSLM Environment is part of the Rule Based Service Level Agreement (RBSLA)
 * framework, available at 
 * <a href=" http://ibis.in.tum.de/staff/paschke/rbsla/index.htm">RBSLA</a>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package rbsla.environment.dialogs;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;

import javax.swing.JDialog;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import org.apache.log4j.Logger;

import rbsla.wrapper.ProvaWrapper;
import rbsla.environment.ECAConstraints;

public class OutputConsole extends JDialog
{
    PipedInputStream piOut;

    PipedInputStream piErr;

    PipedOutputStream poOut;

    PipedOutputStream poErr;

    int idealSize = 100000;

    int maxExcess = 500;

    ProvaWrapper prova = null;

    private Frame parentFrame;

    JTextArea textArea = new JTextArea();

    JScrollPane pane = null;

    public OutputConsole(Frame parent, ProvaWrapper prova) throws IOException
    {

        super(parent, "Output");
        this.prova = prova;

        parentFrame = parent;

        // Add a scrolling text area
        textArea.setEditable(false);
        textArea.setRows(8);
        textArea.setColumns(60);
        textArea.setLineWrap(false);
        textArea.setText("");
        pane = new JScrollPane(textArea);
        getContentPane().add(pane, BorderLayout.CENTER);

        pack();

        OutputLog outputLog = new OutputLog(pane, textArea);
        System.setOut(new PrintStream(outputLog, true)); // set output
        System.setErr(new PrintStream(outputLog, true)); // set err output

        // set console location bottom right of parent frame
        Dimension size = this.getSize();
        Dimension parentSize = parentFrame.getSize();
        Point parentLocation = parentFrame.getLocationOnScreen();
        int diffHeightSize = parentSize.height - size.height;
        int diffWithSize = parentSize.width - size.width;
        this.setLocation(parentLocation.x + diffWithSize, diffHeightSize);

        setResizable(true);
        setVisible(true);
        textArea.requestFocus();

        System.out.println("-------------------------------------------------");
        System.out.println("-                Start Logfile                  -");
        System.out.println("-------------------------------------------------");
    }

}

class OutputLog extends OutputStream
{
    PrintStream outputFile = null;

    private static Logger logger = Logger.getLogger(OutputLog.class);

    JTextArea textArea = null;

    JScrollPane pane = null;

    static int oldMax = 0;

    OutputLog(JScrollPane _pane, JTextArea _textArea)
    {
        pane = _pane;
        textArea = _textArea;
        String outputFilename = ECAConstraints._FILE_BASE_PATH +  "output.log";
        try
        {

            FileOutputStream fileOut = new FileOutputStream(outputFilename,
                    false);
            outputFile = new PrintStream(fileOut);
        } catch (Exception ex)
        {
            logger.info("", ex);
        }
    }

    public void write(int b) throws IOException
    {
        write(new byte[] { (byte) b }, 0, 1);
    }

    public void write(final byte buf[], final int off, final int len)
            throws IOException
    {
        // write to logfile
        outputFile.write(buf, off, len);

        // write to gui
        // TODO Do not scroll output if not at end of file
        final String bufString = new String(buf, off, len);	
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                JScrollBar scrollBar = pane.getVerticalScrollBar();

                boolean pleaseScroll = false;
                if (textArea.getText().length() == 0
                        || (scrollBar.getValue() == oldMax))
                    pleaseScroll = true;

                textArea.append(bufString); // write text

                if (pleaseScroll)
                    scrollBar.setValue(scrollBar.getMaximum());
                oldMax = scrollBar.getValue();

            }
        });

    }
}

