/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package usda.weru.util;

import javolution.context.Context;
//TODO: Perhaps add support for locking the loading to a particular source or bean/object

/**
 *
 * @author Joseph Levin <joelevin@weru.ksu.edu>
 */
public class RestoringContext 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(RestoringContext.class);
        synchronized (LOCK_LATCH) {
            c_latch++;
        }
    }

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

    /**
     *
     * @return
     */
    public static RestoringContext getCurrent() {
        for (Context ctx = Context.getCurrent(); ctx != null; ctx = ctx.getOuter()) {
            if (ctx instanceof RestoringContext) {
                return (RestoringContext) ctx;
            }
        }
        return null;
    }

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

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