/*
 * Queue - A Queueing system that can be used to handle labs in higher education
 * Copyright (C) 2016-2024  Delft University of Technology
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package nl.tudelft.queue.scope;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.web.context.request.AbstractRequestAttributesScope;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * A request-backed {@link org.springframework.beans.factory.config.Scope} implementation which allows a bean
 * to also exist outside a web request.
 * <p>
 * The {@link AbstractRequestAttributesScope} is extended to ensure that a bean is scoped to a request when a
 * requests exist within the thread, and otherwise the bean is made fully available.
 */
public class CacheManager extends AbstractRequestAttributesScope {
	private Map<String, Object> scopedObjects = Collections.synchronizedMap(new HashMap<String, Object>());

	@Override
	public Object get(String name, ObjectFactory<?> objectFactory) {
		if (RequestContextHolder.getRequestAttributes() != null) {
			return super.get(name, objectFactory);
		}
		scopedObjects.put(name, objectFactory.getObject());
		return scopedObjects.get(name);
	}

	@Override
	public Object remove(String name) {
		if (RequestContextHolder.getRequestAttributes() != null) {
			return super.remove(name);
		}
		return scopedObjects.remove(name);
	}

	@Override
	public void registerDestructionCallback(String name, Runnable callback) {
		if (RequestContextHolder.getRequestAttributes() != null) {
			super.registerDestructionCallback(name, callback);
		}
	}

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

	@Override
	protected int getScope() {
		return RequestAttributes.SCOPE_REQUEST;
	}

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