/**
 * Trieda sluzi na citanie log suboru.
 */

package vut.msa.utilities;

import java.io.IOException;
import java.io.RandomAccessFile;
import org.apache.log4j.Logger;

public class LogReader {

    private static Logger log = Logger.getLogger(LogReader.class);
    private RandomAccessFile logFile = null;
    private String lastline = new String();

    public LogReader() {

        String separator = System.getProperty("file.separator");
        try {
            String appPath =
                    FacesServletUtils.getFacesServletUtils().getApplicationFilePath();
            String logFilePath = appPath
                                 + separator
                                 + "logs"
                                 + separator
                                 + "log.txt";
            logFile = new RandomAccessFile(logFilePath, "r"); //chcem iba citat z log suboru

        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }

    /**
     * Metoda vrati posledny riadok z log suboru.
     *
     * @return retazec, posledny riadok log suboru
     */
    public String getLastLine() {

        if (logFile != null) {
            try {
                String temp;
                while ((temp = logFile.readLine()) != null) {
                    if (!lastline.equals(temp)) lastline = temp;
                }

                return lastline;
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
        }

        return null;
    }

    //TODO: Dorobit metodu, ktora bude vracat zadany pocet poslednych riadkov
}
