import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * Datafacer specialized for reading Comma Separated Values format files
 * 
 * @author pdegenne@teledetection.fr
 */
public class Csvfile {

	private final String ERR_HEADER = "Datafacer Csvfile: ";
	private BufferedReader reader;
	private String currentLine;

	/**
	 * Initialize and prepares the .csv file using the file name given in
	 * argument. The file is not read at this point, but it's availability is
	 * being checked. An error message is printed in case of initialization
	 * problem.
	 * 
	 * @param fileName
	 *            Name of the .csv file to read
	 */
	public void setFileName(String fileName) {
		try {
			reader = new BufferedReader(new FileReader(fileName));
		} catch (FileNotFoundException e) {
			System.out.println(ERR_HEADER + "Impossible to open the file "
					+ fileName + " for reading.");
		}
	}

	/**
	 * Checks if there is any more record that has not yet been read
	 * 
	 * @return true is there are more records to be read
	 */
	public boolean hasNextRecord() {
		boolean result = true;
		try {
			currentLine = reader.readLine();
		} catch (IOException e) {
			System.out.println(ERR_HEADER
					+ "An error occured while reading the file.");
			currentLine = null;
		}
		if (currentLine == null)
			result = false;
		return result;
	}

	/**
	 * Returns the next record read from the file.
	 * 
	 * @return A Csvrecord.
	 */
	public Csvrecord getNextRecord() {
		return new Csvrecord(currentLine);
	}

}
