/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.system;

import org.jfox.framework.Component;
import org.jfox.framework.Registry;
import org.jfox.framework.extra.ActiveComponent;
import org.jfox.framework.extra.InstantiatingInterceptable;
import org.jfox.framework.extra.Managable;
import org.jfox.framework.extra.ManagementInfo;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class ShutdownService extends AbstractService implements InstantiatingInterceptable, ActiveComponent, Managable {
    private Registry registry = null;
    private Thread shutdownThread = null;

    public Component afterInstantiate(Component theComp, Registry registry) {
        this.registry = registry;
        return theComp;
    }

    protected void doInit() throws Exception {
        shutdownThread = new Thread(this);
        shutdownThread.setName(getName());

    }

    protected void doStart() throws Exception {
        Runtime.getRuntime().addShutdownHook(shutdownThread);
    }

    protected void doStop() throws Exception {
        // if shutdown thread is working, can not remove it
        if(!shutdownThread.isAlive()) {
            Runtime.getRuntime().removeShutdownHook(shutdownThread);
        }
    }

    protected void doDestroy() throws Exception {
        shutdownThread = null;
    }

    public void run() {
        // do shutdown work
        registry.stop();
        try {
            Thread.sleep(1000L);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    public ManagementInfo getManagementInfo() {
        return ManagementInfo.exposePublic(this.getClass());
    }

    public static void main(String[] args) {

    }
}
