/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * Contact: jonas-team@objectweb.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.objectweb.jonas_lib.deployment.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.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

import org.objectweb.jonas.common.Log;

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

    /**
     * The logger used in JOnAS
     */
    private static Logger logger = Log.getLogger(Log.JONAS_DEPLOY_WORK_PREFIX);

    /**
     * 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 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(File logFile) throws DeployerLogException {
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "logfile=" + logFile.getName());
        }

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

    /**
     * @return the logger
     */
    protected static Logger 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);

                getLogger().log(BasicLevel.DEBUG,
                        "Entry[originalField=" + originalField + ",copyField=" + copyField + "]");
                logEntries.add(new LogEntry(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 e = logEntries.elements(); e.hasMoreElements();) {
            logEntry = (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 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 removeEntry(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 addEntry(File original, 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 e = logEntries.elements();

        //add only if the entry is not found
        while (e.hasMoreElements() && !found) {
            logEntry = (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 LogEntry(original, copy);

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

        //write to the file.
        saveEntries();

        //return the new vector
        return logEntries;
    }

}