package org.ow2.jonas.cluster.daemon;


import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.carol.util.configuration.TraceCarol;

/**
     * Allow stop the cmd childs
     */
public class ShutdownHookThread extends Thread {
    private ClusterDaemon clusterDaemon;

    private Logger logger;


        /**
         * Action at the shutdown : destroy the process.
         */
        public static final int ACTION_DESTROY = 0;

        /**
         * Action at the shutdown : stop the JOnAS instance.
         */
        public static final int ACTION_JONAS_STOP = 1;

        /**
         * Cmdkey.
         */
        private String keyCmd = null;

        /**
         * Action.
         */
        private int action = -1;

        /**
         * JOnAS instance name.
         */
        private String serverName = null;

        /**
         * Constructor.
         *
         * @param keyCmd key command
         */
        public ShutdownHookThread(final String serverName, final String keyCmd,
                                  final int action, ClusterDaemon clusterDaemon,
                                  final Logger logger) {
            this.clusterDaemon = clusterDaemon;
            this.keyCmd = keyCmd;
            this.action = action;
            this.serverName = serverName;
            this.logger = logger;
        }

        /**
         * Thread execution printing information received.
         */
        @Override
        public void run() {
            try {
                if (action == ACTION_DESTROY) {
                    ((Process) clusterDaemon.getProcessMap().get(this.keyCmd)).destroy();
                    logger.log(BasicLevel.DEBUG, "destroy cmd" + keyCmd);
                } else if (action == ACTION_JONAS_STOP) {
                    logger.log(BasicLevel.DEBUG, "stop JOnAS instance " + serverName);
                    clusterDaemon.doStopJOnAS(serverName);
                    logger.log(BasicLevel.DEBUG, "destroy cmd" + keyCmd);
                    ((Process) clusterDaemon.getProcessMap().get(this.keyCmd)).destroy();
                }

            } catch (Exception e) {
                TraceCarol.error("ShutdownHook problem for key=" + this.keyCmd, e);
            }
        }
}