/*
 * MiningMart Version 1.0
 * 
 * Copyright (C) 2006 Martin Scholz, Timm Euler, 
 *                    Daniel Hakenjos, Katharina Morik
 *
 * Contact: miningmart@ls8.cs.uni-dortmund.de
 *
 * A list of contributing developers (other than the copyright 
 * holders) can be found at
 * http://mmart.cs.uni-dortmund.de/downloads/download.html
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program, see the file MM_HOME/LICENSE; if not, write
 * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 * Floor, Boston, MA 02110-1301, USA.
 */
package edu.udo.cs.miningmart.gui.application;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.musoft.limo.application.Application;
import org.musoft.limo.application.Resource;

import edu.udo.cs.miningmart.m4.M4Interface;
import edu.udo.cs.yale.gui.SearchDialog;

/**
 * A JPanel for the logging.
 * @author Daniel Hakenjos
 * @version $Id: PrintViewer.java,v 1.3 2006/04/11 14:10:16 euler Exp $
 */
public class PrintViewer extends JPanel implements ActionListener{

	/** A special output stream that appends all its incoming characters to the text field as soon
	 *  as it reads a newline. */
	private class PrintViewerOutputStream extends OutputStream {
		private StringBuffer currentString;

		private PrintViewerOutputStream() {
			this.currentString = new StringBuffer();
		}
		
		public void write(int b) {
//			System.out.println("write(int b)");
			char c = (char) b;
			switch (b) {
				case 0x000a :
				case 0x000d :
                if (currentString.length() > 0) {
                	//System.out.println("nextline");
                    logarea.append(currentString.toString() + "\n");
                    logarea.setCaretPosition(logarea.getDocument().getLength());
                    currentString = new StringBuffer();
                }
                break;
				case '\t' :
					currentString.append("   ");
					break;
				default :{
					try{
						currentString.append(c);
						if (false) throw new IOException(); // bit of a hack...
						break;
					}catch(IOException error){
						error.printStackTrace();
					}
				}
			}
		}

		public void clear() {
			currentString = new StringBuffer();
		}
		/* (non-Javadoc)
		 * @see java.io.OutputStream#write(byte[], int, int)
		 */
		public void write(byte[] b, int off, int len) throws IOException {
			for(int i=off;i<len;i++)
				write((char) b[i]);
			logarea.append(currentString.toString());
			currentString=new StringBuffer();
			logarea.setCaretPosition(logarea.getDocument().getLength()); 
		}

		/* (non-Javadoc)
		 * @see java.io.OutputStream#write(byte[])
		 */
		public void write(byte[] b) throws IOException {
			for(int i=0;i<b.length;i++)
				write((char) b[i]);
			logarea.append(currentString.toString());
			currentString=new StringBuffer();
			logarea.setCaretPosition(logarea.getDocument().getLength()); 
		}
		
		public void write(char c){
			try{
				currentString.append(c);
				if (false) throw new IOException(); // bit of a hack...
			}catch(IOException error){
				error.printStackTrace();
			}
		}

	}

	/** A stream that can be used to print to this text area. */
	public final PrintViewerOutputStream outputStream = new PrintViewerOutputStream();

	// GUI Objects

	private JTextArea logarea;
	private JScrollPane scrollpane;
	private String name;

	private JPanel panel;
	
	private Application app;
	
	private PrintViewHandler handler;

	/**
	 * Constructor for PrintViewer.
	 */
	public PrintViewer(Application app) {
		this.app=app;
		initPrintViewer();
		initComponents();
	}

	private void initPrintViewer() {
		this.name = Resource.getString("LOGSERVICE");
//		M4Interface.print.addOutputStream(outputStream);
		handler=new PrintViewHandler(outputStream);
		M4Interface.print.addHandler(handler);
	}
	
	public void closePrintViewer(){
//		M4Interface.print.removeOutputStream(outputStream);
		M4Interface.print.removeHandler(handler);
	}

	private void initComponents() {
		logarea = new JTextArea(100, 200);
		logarea.setBackground(Color.WHITE);
		logarea.setForeground(Color.BLACK);
//		logarea.setText("starting Application with new case\n");
		logarea.setEditable(false);
		scrollpane = new JScrollPane(logarea);
		setLayout(new BorderLayout());
		add(scrollpane, BorderLayout.CENTER);


        JPanel panel=new JPanel();
        panel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        BoxLayout boxlay=new BoxLayout(panel,BoxLayout.X_AXIS);
        panel.setLayout(boxlay);

        JButton clearButton=new JButton(Resource.getString("CLEAR_VIEWER"));
        clearButton.addActionListener(this);
        JButton saveButton=new JButton(Resource.getString("SAVE_VIEWER"));
        saveButton.addActionListener(this);
        JButton findButton=new JButton(Resource.getString("FIND_VIEWER"));
        findButton.addActionListener(this);
		panel.add(Box.createHorizontalGlue());
        panel.add(clearButton);
        panel.add(saveButton);
        panel.add(findButton);
        add(panel,BorderLayout.SOUTH);

	}

	public String toString() {
		return name;
	}

	public String getLogMessage() {
		return logarea.getText();
	}

	public void clear() {
		outputStream.clear();
		logarea.setText("");
	}
	
	

	/**
	 * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		//System.out.println(outputStream.currentString.toString());
		
		String cmd=e.getActionCommand();
		if (cmd.equals(Resource.getString("CLEAR_VIEWER"))){
			clear();
		}
		if (cmd.equals(Resource.getString("SAVE_VIEWER"))){
	        String f=null;//=getParameterAsString("ImageFile");
			File file;
	
	        JFileChooser chooser = new JFileChooser(((MiningMartApplication) app).getWorkingDir());
	        chooser.addChoosableFileFilter(new LogFileFilter());
	        
	        int returnVal = chooser.showSaveDialog(app);

	        if (returnVal != JFileChooser.APPROVE_OPTION) 
	        	return;

            file = chooser.getSelectedFile();

            if (file != null) {

		        if (file.exists()) {
		            //abfangen ob die existierende Datei ueberschrieben werden soll
		            int confirm = JOptionPane.showConfirmDialog(this,
		                    Resource.getString("DIALOG_OVERWRITE_FILE")+" "
		                            + file.getName() + "?", Resource.getString("DIALOG_OVERWRITE_TITLE"),
		                    JOptionPane.YES_NO_OPTION);
		            if (confirm != JOptionPane.YES_OPTION) {
		                return;
		            }
		        }


                try {
                    PrintWriter out = new PrintWriter(new FileWriter(file));
                    out.println(logarea.getText());
                    out.close();
                } catch (IOException ex) {
                    //SwingTools.showErrorMessage("Cannot write log file.", ex);
                }
            }
		}
		if (cmd.equals(Resource.getString("FIND_VIEWER"))){
            new SearchDialog(PrintViewer.this, logarea).setVisible(true);
		}
	}

}
/*
$Log: PrintViewer.java,v $
Revision 1.3  2006/04/11 14:10:16  euler
Updated license text.

Revision 1.2  2006/04/06 16:31:15  euler
Prepended license remark.

Revision 1.1  2006/01/03 09:54:27  hakenjos
Initial version!

*/
