package eu.dnetlib.dlms.benchmark;

import java.io.FileWriter;
import java.io.IOException;

/**
 * A custom log writer that flushes to file each message is written.
 * 
 * @author lexis
 */
public class CustomLogger {
	/**
	 * Path to the destination file for custom log messages. Used to get info about the file processed when everything
	 * crashes for the OutOfMemory exception.
	 */
	private String synchLogFilePath;
	/**
	 * FileWriter to write in the file at path this.synchLogFilePath.
	 */
	private FileWriter synchLogWriter;

	/**
	 * Sets the destination path of the custom logger, creating a new FileWriter at the given location. if
	 * this.synchLogWriter is not null, then it is closed before the new assignemnt is executed.
	 * 
	 * @param synchLogFilePath
	 *            destination path of the custom log
	 * @throws IOException
	 *             if a new FileWriter cannot be created at the given location
	 */
	public void setSynchLogFilePath(final String synchLogFilePath) throws IOException {
		this.synchLogFilePath = synchLogFilePath;
		if (this.synchLogWriter != null)
			this.synchLogWriter.close();
		this.synchLogWriter = new FileWriter(this.synchLogFilePath);
	}

	public String getSynchLogFilePath() {
		return this.synchLogFilePath;
	}

	public void setSynchLogWriter(final FileWriter synchLogWriter) {
		this.synchLogWriter = synchLogWriter;
	}

	public FileWriter getSynchLogWriter() {
		return this.synchLogWriter;
	}

	/** No args constructor. */
	public CustomLogger() {
	}

	/**
	 * Constructor.
	 * 
	 * @param path
	 *            destination path of the logs
	 * @throws IOException
	 *             if a new FileWriter cannot be created at the given location
	 */
	public CustomLogger(final String path) throws IOException {
		this.synchLogFilePath = path;
		this.synchLogWriter = new FileWriter(this.synchLogFilePath);
	}

	/**
	 * Writes the given string to file and flushes. If the synchLogWriter is null, then nothing happens.
	 * 
	 * @param str
	 *            message to write to file
	 * @throws IOException
	 *             if the string cannot be written or the FileWriter cannot be flushed
	 */
	public void write(final String str) throws IOException {
		if (this.synchLogWriter != null) {
			this.synchLogWriter.write(str);
			this.synchLogWriter.write("\n");
			this.synchLogWriter.flush();
		}
	}

	/**
	 * Flushes and closes the FileWriter. If the FileWriter is null, then nothing happens.
	 * 
	 * @throws IOException
	 *             closing the FileWriter
	 */
	public void close() throws IOException {
		if (this.synchLogWriter != null)
			this.synchLogWriter.close();
	}
}
