/*
 * 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 LoadingContext 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(LoadingContext.class);
        synchronized(LOCK_LATCH){
            c_latch++;
        }
    }

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

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

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

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