/**
 * 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$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.work;

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.DeployerLogException;
import org.ow2.jonas.workcleaner.LogEntry;

/**
 * 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 extends AbsDeployerLog<LogEntry> {

    /**
     * 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 {
        super(logFile);
    }

    /**
     * load the entries of the log file.
     * @throws DeployerLogException if the load failed.
     */
    protected 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.
     */
    protected 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();
    }

    @Override
    public Vector<LogEntry> addEntry(LogEntry logEntry) 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
        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 entry = e.nextElement();
            originalEntry = entry.getOriginal();
            copyEntry = entry.getCopy();

            if (originalEntry.getPath().equals(logEntry.getOriginal().getPath())
                    && copyEntry.getPath().equals(logEntry.getCopy().getPath())) {
                found = true;
            }
        }
        if (found) {
            return logEntries;
        }

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

        //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 =  new LogEntryImpl(original, copy);

        return addEntry(logEntry);
    }

    /**
     * @param original Original File
     * @return the entry which match with the orginal file
     */
    public LogEntry getEntry(File original) {

        for (LogEntry logEntry: this.logEntries) {

            if (logEntry.getOriginal().equals(original)) {
                return logEntry;
            }
        }

        return null;
    }

}