/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial developer(s): Florent BENOIT & Ludovic BERT
 * --------------------------------------------------------------------------
 * $Id: DeployerLog.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.work;

//import java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;

import org.ow2.jonas.workcleaner.LogEntry;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;


/**
 * Class which permits to store or load the association between the name of a package and the timestamped work copy associated.
 * @author Florent Benoit
 * @author Ludovic Bert
 */
public class DeployerLog {

    /**
     * The logger.
     */
    private Log logger = LogFactory.getLog(DeployerLog.class);

    /**
     * Separator char of a entry in the log file.
     */
    private static final String SEPARATOR_ENTRY = ";";

    /**
     * File for logging.
     */
    private File logFile;

    /**
     * The current entries of the logFile.
     */
    private Vector<LogEntry> logEntries = null;

    /**
     * Constructor for the deployerLog.
     * @param logFile the file which is used for read/write entries
     * @throws DeployerLogException if the loadentries failed.
     */
    public DeployerLog(final File logFile) throws DeployerLogException {
        logger.debug("logfile=" + logFile.getName());

        this.logFile = logFile;
        logEntries = new Vector<LogEntry>();
        loadEntries();
    }

    /**
     * @return the logger
     */
    protected Log getLogger() {
        return logger;
    }

    /**
     * load the entries of the log file.
     * @throws DeployerLogException if the load failed.
     */
    private synchronized void loadEntries() throws DeployerLogException {

        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(logFile));
        } catch (FileNotFoundException e) {
            throw new DeployerLogException("Can not read the " + logFile + " file");
        }
        String line = null;

        String field = null;
        File originalField = null;
        File copyField = null;
        StringTokenizer st = null;

        try {
            //Read the text file
            while ((line = br.readLine()) != null) {

                //parse the String
                st = new StringTokenizer(line, SEPARATOR_ENTRY);
                field = st.nextToken();
                if (field == null) {
                    throw new DeployerLogException("Inconsistent line in the file " + logFile);
                }
                originalField = new File(field);

                field = st.nextToken();
                if (field == null) {
                    throw new DeployerLogException("Inconsistent line in the file " + logFile);
                }

                copyField = new File(field);

                logger.debug("Entry[originalField=" + originalField + ",copyField=" + copyField + "]");
                logEntries.add(new LogEntryImpl(originalField, copyField));
            }
            // Close the input stream
            br.close();
        } catch (IOException ioe) {
            throw new DeployerLogException("Error while reading the log file " + logFile + " :" + ioe.getMessage());
        }
    }

    /**
     * Dump(save) the entries to the log file.
     * @throws DeployerLogException if the save failed.
     */
    private synchronized void saveEntries() throws DeployerLogException {

        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new BufferedWriter(new FileWriter(logFile)));
        } catch (IOException e) {
            throw new DeployerLogException("Problem while trying to get an output stream for the " + logFile + " file");
        }

        LogEntry logEntry = null;
        String original = null;
        String copy = null;
        String line = null;
        for (Enumeration<LogEntry> e = logEntries.elements(); e.hasMoreElements();) {
            logEntry = e.nextElement();

            //get the infos

            try {
                original = logEntry.getOriginal().getCanonicalPath();
                copy = logEntry.getCopy().getCanonicalPath();
            } catch (IOException ioe) {
                throw new DeployerLogException("Problem while trying to get files names ");
            }

            //create the line
            line = original + SEPARATOR_ENTRY + copy;

            //dump the line
            pw.println(line);
        }
        // Close the stream
        pw.close();
    }

    /**
     * Return the entries of the file.
     * @return a vector of LogEntry item.
     */
    public synchronized Vector<LogEntry> getEntries() {
        return logEntries;
    }

    /**
     * Remove the given entry and return the entries of the file.
     * @param entry the LogEntry which must be remove.
     * @return the new vector of LogEntry item.
     * @throws DeployerLogException if the remove can't be done
     */
    public synchronized Vector<LogEntry> removeEntry(final LogEntry entry) throws DeployerLogException {
        if (logEntries == null) {
            throw new DeployerLogException("Can not remove a entry, the vector is null");
        }

        if (!logEntries.contains(entry)) {
            throw new DeployerLogException("Can not remove entry " + entry + ". There is no such entry");
        }

        //remove can be done
        logEntries.remove(entry);

        //write to the file.
        saveEntries();

        //return the new vector
        return logEntries;
    }

    /**
     * Add the entry and return the new entries.
     * @param original the name of the file
     * @param copy the copy of the file
     * @return the new vector of LogEntry item.
     * @throws DeployerLogException if the add can't be done
     */
    public synchronized Vector<LogEntry> addEntry(final File original, final File copy) throws DeployerLogException {
        if (logEntries == null) {
            throw new DeployerLogException("Can not add an entry, the vector is null");
        }

        //add only if it's not already present
        LogEntry logEntry = null;
        File originalEntry = null;
        File copyEntry = null;

        boolean found = false;
        Enumeration<LogEntry> e = logEntries.elements();

        //add only if the entry is not found
        while (e.hasMoreElements() && !found) {
            logEntry = e.nextElement();

            originalEntry = logEntry.getOriginal();
            copyEntry = logEntry.getCopy();

            if (originalEntry.getPath().equals(original.getPath()) && copyEntry.getPath().equals(copy.getPath())) {
                found = true;
            }
        }
        if (found) {
            return logEntries;
        }

        //add entry
        logEntry = new LogEntryImpl(original, copy);

        //add can be done
        logEntries.add(logEntry);

        //write to the file.
        saveEntries();

        //return the new vector
        return logEntries;
    }

}