/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2008 Bull S.A.S.
 * 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): Benoit PELLETIER
 * --------------------------------------------------------------------------
 * $Id: AbsCleanTask.java 21888 2011-11-06 17:48:21Z cazauxj $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.work;

import java.io.File;
import java.util.Enumeration;
import java.util.Vector;

import org.ow2.jonas.workcleaner.CleanTask;
import org.ow2.jonas.workcleaner.DeployerLogException;
import org.ow2.jonas.workcleaner.IDeployerLog;
import org.ow2.jonas.workcleaner.LogEntry;
import org.ow2.jonas.workcleaner.WorkCleanerException;
import org.ow2.util.file.FileUtils;
import org.ow2.util.file.FileUtilsException;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * Abstract Clean Task class which define a generic job executed by the cleaner thread.
 * @author Benoit PELLETIER
 */
public abstract class AbsCleanTask implements CleanTask {

    /**
     * Logger.
     */
    private Log logger = LogFactory.getLog(AbsCleanTask.class);

    /**
     * Default constructor : Construct a new cleaner.
     */
    protected AbsCleanTask() {
    }

    /**
     * Check if the package pointed by the log entry is currently deploy.
     * @param logEntry entry in a deploy log
     * @return true if the package pointed by the log entry is currently deployed
     * @throws WorkCleanerException If it fails
     */
    protected abstract boolean isDeployedLogEntry(LogEntry logEntry) throws WorkCleanerException;

    /**
     * Returns the {@link IDeployerLog} of the task.
     * @return The DeployerLog of the task
     */
    public abstract IDeployerLog getDeployerLog();

    /**
     * Return true if the work copy exists and is up to date.
     * @param logEntry entry in a deploy log
     * @return true if the work copy exists and is up to date
     * @throws WorkCleanerException if it fails
     */
    public boolean isValidLogEntry(final LogEntry logEntry) throws WorkCleanerException {
        String lastModifiedFileName = null;
        File logEntryFile = logEntry.getOriginal();
        String logEntryUnpackedDir = logEntry.getCopy().getName();

        logger.debug("LogEntry <" + logEntryFile.getName() + "> exists :" + logEntryFile.exists());

        // If the file doesn't exist, return
        if (!logEntryFile.exists()) {
            return false;
        }

        // Get the file name containing the last modification date
        try {
            lastModifiedFileName = FileUtils.lastModifiedFileName(logEntryFile);
        } catch (FileUtilsException e) {
            logger.error("Cannot retrieve the working file name for the deployable '{0}'", logEntryFile);
        }

        logger.debug("LogEntry lastModificationFileName :" + lastModifiedFileName);
        logger.debug("LogEntry isValid :" + lastModifiedFileName.equalsIgnoreCase(logEntryUnpackedDir));

        // Compare the two file names
        return (lastModifiedFileName.equalsIgnoreCase(logEntryUnpackedDir));

    }

    /**
     * Run the clean task.
     * @throws WorkCleanerException if it failed.
     */
    public void execute() throws WorkCleanerException {
        logger.debug("Execute called");

        // Get the entries from the logger
        Vector<LogEntry> logEntries = getLogEntries();

        // Check if the files in this vector exists
        LogEntry logEntry = null;

        for (Enumeration<LogEntry> e = logEntries.elements(); e.hasMoreElements();) {
            logEntry = e.nextElement();
            logger.debug("LogEntry <" + logEntry.getOriginal().getName() + "," + logEntry.getCopy().getName() + ">");

            // If the package is deployed, do nothing
            if (isDeployedLogEntry(logEntry)) {
                logger.debug("LogEntry currently deployed - > do nothing");
                continue;
            }

            // If the source package file doesn't exists anymore or if the file is present but don't care the right last
            // modification date
            if (!isValidLogEntry(logEntry)) {

                // We try to remove the entry
                if (removeLogEntry(logEntry)) {
                    // Enumeration is now inconsistent, so we 're restarting the loop
                    e = logEntries.elements();
                }
            }
            // Else last modification dates always the same
        }
    }

    /**
     * Remove the work copy specified in the log entry and the log entry.
     * @param logEntry entry in a deploy log
     * @return true if the log entry has been removed successfully
     * @throws WorkCleanerException if it fails
     */
    public boolean removeLogEntry(final LogEntry logEntry) throws WorkCleanerException {
        if (FileUtils.delete(logEntry.getCopy())) {
            try {
                getDeployerLog().removeEntry(logEntry);
                return true;
            } catch (DeployerLogException edle) {
                throw new WorkCleanerException("Can't remove an entry" + edle.getMessage());
            }
        }
        return false;
    }

    /**
     * Gets the log entries.
     * @return the log entries
     */
    public Vector<LogEntry> getLogEntries() {
        return getDeployerLog().getEntries();
    }

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