/**
 * 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.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;

/**
 * JOnAS work deployment files and directories cleaner class. This class
 * provides a way for removing entries wich are unconsistent.
 * @author Florent Benoit
 * @author Ludovic Bert
 * @author Benoit PELLETIER
 */
public class WorkCleaner extends Thread {

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

    /**
     * Sleep time for the thread of the cleaner
     */
    private static final int SLEEP_TIME = 300000;

    /**
     * the instance of this VM. There is only one instance of the cleaner
     * running in the same VM.
     */
    private static WorkCleaner unique = null;

    /**
     * The list of tasks to execute at each period
     */
    private Vector taskList = null;

    /**
     * Default constructor : Construct a new cleaner.
     */
    private WorkCleaner() {
        super("WorkCleaner");
        // set a low priority for this thread in order to reduce
        // the impacts on 'functionnal' threads.
        this.setPriority(Thread.MIN_PRIORITY);
        taskList = new Vector();
    }

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

    /**
     * Get an instance of the Work Cleaner.
     * @return the instance of the Work Cleaner.
     */
    public static synchronized WorkCleaner getInstance() {
        if (unique == null) {
            unique = new WorkCleaner();
        }
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "getInstance : ->" + unique);
        }
        return unique;
    }

    /**
     * Register a new clean task
     * @param absCleanTask the task to add
     * @throws CleanerException if the task cannot be registred
     */
    public synchronized void registerTask(AbsCleanTask absCleanTask) throws CleanerException {
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "registerTask : called");
        }
        // checks
        if (taskList == null) {
            throw new CleanerException("Can not add an entry, the vector is null");
        }
        if (absCleanTask == null) {
            throw new CleanerException("Can not add a null entry");
        }
        // Add if don't already exist
        if (!taskList.contains(absCleanTask)) {
            taskList.add(absCleanTask);
        }
    }

    /**
     * Execute the registered tasks
     */
    public synchronized void executeTasks() {
        try {
            AbsCleanTask absCleanTask = null;

            if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                getLogger().log(BasicLevel.DEBUG, "executeTasks : wake up");
            }
            for (Enumeration e = taskList.elements(); e.hasMoreElements();) {

                absCleanTask = (AbsCleanTask) e.nextElement();
                absCleanTask.execute();
            }

        } catch (CleanerException e) {
            e.printStackTrace();
        }
    }

    /**
     * Start the thread of this class It will clean all the work entries
     */
    public void run() {

        for (;;) {
            executeTasks();
            try {
                Thread.sleep(SLEEP_TIME);
            } catch (InterruptedException e) {
                throw new RuntimeException("Thread fail to sleep");
            }
        }
    }

}
