/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.tenant.context;

/**
 * For handling the association TenantContext / Thread
 * @author Mohammed Boukada
 */
public class TenantCurrent {
    /**
     * Local thread
     */
    private static InheritableThreadLocal threadTctx;

    /**
     * Tenant Context for all the JVM
     */
    private static TenantContext tctx = null;

    /**
     * Init the thread
     */
    static {
        threadTctx = new InheritableThreadLocal();
        threadTctx.set(new TenantContext());
    }

    /**
     * Unique instance
     */
    private static TenantCurrent current = new TenantCurrent();

    /**
     * Method getCurrent
     * @return TenantCurrent return the current
     */
    public static TenantCurrent getCurrent() {
        return current;
    }

    /**
     * Method setTenantContext
     * @param ctx Tenant context to associate to the current thread
     */
    public void setTenantContext(TenantContext ctx) {
        threadTctx.set(ctx);
    }

    /**
     * Method setTenantContext used for client container
     * @param ctx Tenant context to associate to the JVM
     */
    public void setGlobalTenantContext(TenantContext ctx) {
        TenantCurrent.tctx = ctx;
    }

    /**
     * Method getTenantContext
     * @return TenantContext return the Tenant context associated to the
     *         current thread
     */
    public TenantContext getTenantContext() {
        if (tctx != null) {
            return tctx;
        } else {
            return (TenantContext) threadTctx.get();
        }
    }
}
