/**
 * @(#)ReadFiles.java
 *
 * <code>ReadFiles</code> class handles some duties like
 * reading txt files or creating the Open File dialog.
 * 
 * @author Gokhan Arici
 * @version 1.00 21.12.2009
 */

package bin;
 
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.util.Scanner;
import java.io.*;

public class ReadFiles {
	
	/**
	 * <code>path</code><br>
	 * Path for Open Dialog.
	 */
	private String path;
		
	/**
	 * The default constructor. Creates an Open Dialog 
	 * for TXT files and stores the file path in 
	 * <code>path</code> variable. May throw an 
	 * <code>Exception</code> if "Open" is not chosen.
	 * @throws An Exception if the file could not be 
	 * found or another error has occured.
	 */
    public ReadFiles () throws Exception {
    	// Initialize returnVal
		int returnVal = -1;
		// Create a JFileChooser, set the default path to "./books/"
		JFileChooser chooser = new JFileChooser("./books/");
		// Show only TXT Files
		FileNameExtensionFilter filter = new FileNameExtensionFilter(Language.getText(15), "txt");
		// Apply the extension filter
		chooser.setFileFilter(filter);
		// Read the value
 		returnVal = chooser.showOpenDialog(null);
 		// If returnVal is not "Open"
		if (returnVal != JFileChooser.APPROVE_OPTION)
			// Throw a new exception
			throw new Exception();
    	// Set the path to the selected file's path
		path=chooser.getSelectedFile().getPath();
    }
    
	/**
	 * <code>getPath</code><br>
	 * Used for accessing the path saved by the constructor.
	 * @return The path of the file.
	 */
    public String getPath() {
    	// Return the path
    	return path;
    }
    
	/**
	 * <code>readPlainFile</code><br>
	 * Returns the content of the file as a String.
	 * May throw an <code>Exception</code> if an error occurs.
	 * @param bookPath The path of the book.
	 * @return A String object to store the read book.
	 */
    public static String readPlainFile (String bookPath) throws Exception {
    	// Create a new Scanner object to read bookPath
		Scanner bookscanner = new Scanner(new FileInputStream(bookPath));
		// The trick is here: -1 doesn't represent any character, so if we
		// use it as the delimiter, Scanner object cannot split the book.
		// Therefore, the first and the only token is the book itself.
		bookscanner.useDelimiter( ""+(char)-1 );
		// Return the book
		return bookscanner.next();
    }
}
