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

package org.objectweb.jonas_lib.deployment.work;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;

import org.objectweb.jonas.service.ServiceManager;
import org.objectweb.jonas.ear.EarService;

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

/**
 * JOnAS Ear unused directory clean task class. This class provides a way for
 * removing directories wich are unconsistent directories for ear files.
 * @author Florent BENOIT
 * @author Benoit PELLETIER
 */
public class EarCleanTask extends AbsCleanTask {

    /**
     * reference to the deployerLog
     */
    private static DeployerLog earDeployerLog = null;

    /**
     * Url of the jonas_ROOT/apps directory
     */
    private static URL earAppsUrl = null;

    /**
     * Default constructor : Construct a new cleaner.
     * @param earApps the jonasroot apps directory
     * @param earDeployerLog the deployer logger
     */
    public EarCleanTask(URL earApps, DeployerLog earDeployerLog) {
        super();
        EarCleanTask.earAppsUrl = earApps;
        EarCleanTask.earDeployerLog = earDeployerLog;
    }

    /**
     * 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 CleanerException if it fails
     */
    protected boolean isValidLogEntry(LogEntry logEntry) throws CleanerException {
        String fTimeStamp = null;
        File earLogEntryFile = logEntry.getOriginal();
        String earLogEntryUnpackedDir = logEntry.getCopy().getName();
        //File dirEar = new File(earAppsUrl.getFile() + File.separator + earLogEntryUnpackedDir);
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG,
                    "LogEntry <" + earLogEntryFile.getName() + "> exist :" + earLogEntryFile.exists());
        }

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

        //get the timestamp
        try {
            fTimeStamp = FileManager.fileToTimeStampDir(earLogEntryFile.toURL());
        } catch (FileManagerException efme) {
            throw new CleanerException("Can't get the timestamp of the file " + earLogEntryFile + " : "
                    + efme.getMessage());
        } catch (MalformedURLException mue) {
            throw new CleanerException("Can't get the timestamp of the file " + earLogEntryFile + " : "
                    + mue.getMessage());
        }

        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "LogEntry fTimeStamp :" + fTimeStamp);
            getLogger().log(BasicLevel.DEBUG, "LogEntry isValid :" + fTimeStamp.equalsIgnoreCase(earLogEntryUnpackedDir));
        }

        //compare
        return (fTimeStamp.equalsIgnoreCase(earLogEntryUnpackedDir));

    }

    /**
     * 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 boolean removeLogEntry(LogEntry logEntry) throws CleanerException {
        if (removeRecursiveDirectory(logEntry.getCopy())) {
            try {
                earDeployerLog.removeEntry(logEntry);
                return true;
            } catch (DeployerLogException edle) {
                throw new CleanerException("Can't remove an entry" + edle.getMessage());
            }
        }
        return false;
    }

    /**
     * Gets the log entries
     * @return the log entries
     */
    protected Vector getLogEntries() {
        return earDeployerLog.getEntries();
    }

    /**
     * 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 boolean isDeployLogEntry(LogEntry logEntry) throws CleanerException {

        // get the ear service
        ServiceManager sm = null;

        try {
            sm = ServiceManager.getInstance();
        } catch (Exception e) {
            throw new CleanerException("Cannot get ServiceManager instance");
        }
        EarService earService = (EarService) sm.getEarService();

        // check if the ear file is deployed
        return earService.isEarDeployedByUnpackName(logEntry.getCopy().getName());
    }
}