/**
 * 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): Benoit PELLETIER
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas_lib.deployment.work;

import java.io.File;

import java.util.Enumeration;
import java.util.Vector;

import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

import org.objectweb.jonas.common.Log;

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

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

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

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

    /**
     * Abstract method defined in the derived classes return true if the work
     * copy exist 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 CleanerException if it fails
     */
    protected abstract boolean isValidLogEntry(LogEntry logEntry) throws CleanerException;

    /**
     * Abstract method defined in the derived classes 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 CleanerException if it fails
     */
    protected abstract boolean removeLogEntry(LogEntry logEntry) throws CleanerException;

    /**
     * Abstract method defined in the derived classes get the log entries
     * @return the log entries
     */
    protected abstract Vector getLogEntries();

    /**
     * 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 CleanerException if it fails
     */
    protected abstract boolean isDeployLogEntry(LogEntry logEntry) throws CleanerException;

    /**
     * Run the clean task
     * @throws CleanerException if it failed.
     */
    public void execute() throws CleanerException {

        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "execute : called");
        }

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

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

        for (Enumeration e = logEntries.elements(); e.hasMoreElements();) {

            logEntry = (LogEntry) e.nextElement();
            if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                getLogger().log(BasicLevel.DEBUG,
                        "LogEntry <" + logEntry.getOriginal().getName() + "," + logEntry.getCopy().getName() + ">");
            }

            // if the package is deployed, do nothing
            if (isDeployLogEntry(logEntry)) {
                if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                    getLogger().log(BasicLevel.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 timestamp
            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 time stamp always the same
        }
    }

    /**
     * Remove a directory with all its child (recursive)
     * @param file the file or directory which must be deleted
     */
    protected boolean removeRecursiveDirectory(File file) {
        // If the file doesn't exists, the removal of the file is useless
        if (!file.exists()) {
            return true;
        }
        
        if (file.isFile()) {
            return file.delete();
        }
        // else (if directory)
        File[] children = file.listFiles();
        if (children == null) {
            // no children
            return file.delete();
        }

        // There are children
        boolean result = true;
        for (int i = 0; i < children.length; i++) {
            result &= removeRecursiveDirectory(children[i]);
        }
        return result && file.delete();
    }
}