package usda.weru.util;

import javolution.context.Context;

/**
 *
 * @author Joseph Levin <joelevin@weru.ksu.edu>
 */
public class FireAllContext extends Context {

    private static final long serialVersionUID = 1L;

    private static final Object LOCK_LATCH = new Object();
    private static int c_latch;

    /**
     *
     */
    @Override
    protected void enterAction() {

    }

    /**
     *
     */
    @Override
    protected void exitAction() {

    }

    /**
     *
     */
    public static void enter() {
        Context.enter(FireAllContext.class);
        synchronized (LOCK_LATCH) {
            c_latch++;
        }
    }

    /**
     *
     */
    public static void exit() {
        Context.exit(FireAllContext.class);
        synchronized (LOCK_LATCH) {
            c_latch--;
        }
    }

    /**
     *
     * @return
     */
    public static FireAllContext getCurrent() {
        for (Context ctx = Context.getCurrent(); ctx != null; ctx = ctx.getOuter()) {
            if (ctx instanceof FireAllContext) {
                return (FireAllContext) ctx;
            }
        }
        //TODO: add a default context
        return null;
    }

    /**
     *
     * @return
     */
    public static boolean isInFireAll() {
        return isInFireAll(false);
    }

    /**
     *
     * @param anyThread
     * @return
     */
    public static boolean isInFireAll(boolean anyThread) {
        if (anyThread) {
            return c_latch > 0;
        } else {
            return getCurrent() != null;
        }
    }

}
