/***************************************************************************
 * Copyright 2014 Kieker Project (http://kieker-monitoring.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ***************************************************************************/

package kieker.webgui.web.utility;

import java.util.Map;

import javax.faces.context.FacesContext;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * This is an own implementation of the view scope of Java Server Faces. This is necessary as Spring does not provide this scope. The implementation is merely
 * rudimentary. For example, it does not provide destruction callbacks or the resolving of contextual objects. The code originates from {@code blog.primefaces.org}.
 * We register the scope in the configuration file {@code spring-common-config.xml}. It can be used as any other Spring scope using the
 * {@link org.springframework.context.annotation.Scope} annotation with the value {@code view}.
 * 
 * @author Nils Christian Ehmke
 */
public final class ViewScope implements Scope {

	/**
	 * Default constructor. <b>Do not use this constructor. This scope is Spring managed.</b>
	 */
	public ViewScope() {
		// No code necessary.
	}

	@Override
	public Object get(final String name, final ObjectFactory<?> objectFactory) {
		final Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();

		if (viewMap.containsKey(name)) {
			return viewMap.get(name);
		} else {
			final Object object = objectFactory.getObject();
			viewMap.put(name, object);

			return object;
		}
	}

	@Override
	public Object remove(final String name) {
		return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name);
	}

	@Override
	public String getConversationId() {
		return null;
	}

	@Override
	public void registerDestructionCallback(final String name, final Runnable callback) { // NOPMD (Threads are not used here)
		// Destruction callback is not supported
	}

	@Override
	public Object resolveContextualObject(final String key) {
		return null;
	}

}
