/*
 *
 * Copyright (C)  3-mar-2004 Jean-Yves Beaujean 
 * 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; if not, write to the Free Software Foundation, Inc.,  59
 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.

 * 
 */
package jxtray.io;

import javax.swing.JTextArea;
import javax.swing.BorderFactory;

import java.io.File;
import java.io.FileInputStream;
import javax.swing.JFileChooser;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.awt.Dimension;


/** This code is inspired by an example of a book :
 *  Java/IO  - Elliotte Rusty Harold - ed. Oreilly
 * 
 */

public class TextFilePreview extends JTextArea implements PropertyChangeListener
{
	
	private String preview = "";
	private File selectedFile = null;
	
	public TextFilePreview(JFileChooser fc)
	{
		super(10,20);
		this.setEditable(false);
		this.setPreferredSize(new Dimension(150,150));
		this.setLineWrap(true);
		this.setBorder(BorderFactory.createEtchedBorder());
		fc.addPropertyChangeListener(this);
		
	}
	
	public void loadText()
	{
		if ( selectedFile != null)
		try
		{
			if ( selectedFile.isDirectory() )
			{
				preview = "";
				return;
			}
					
			FileInputStream in = new FileInputStream(selectedFile);
			byte[] data = new byte[250];
			int byteRead=0;
			for ( int i=0; i < 250; i++)
			{
				int b=in.read();
				if ( b==-1)
					break;
				byteRead++;
				data[i]= (byte) b;
			}
			preview = new String(data,0,byteRead);
			in.close();
		}
		catch( Exception e )
		{
			preview = "Preview error";
		}
	}
	
	public void propertyChange ( PropertyChangeEvent e )
	{
		if ( e.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY))
		{
			selectedFile = (File) e.getNewValue();
			if ( isShowing() )
			{
				loadText();
				this.setText(preview);
			}
		}
	}
	

}
