package org.gcube.application.cms.caches;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.gcube.application.geoportal.common.model.rest.ConfigurationException;
import org.gcube.application.geoportal.common.utils.ContextUtils;

@Slf4j
/**
 * TTL Map Context -> T
 *
 */
public abstract class AbstractScopedMap<T> extends TimedMap<String,T> implements Engine<T>{

	public AbstractScopedMap(@NonNull String name) {
		super(name);
	}

	@Override
	public T getObject() throws ConfigurationException {
		return get(ContextUtils.getCurrentScope());
	}


	@Override
	public void init() {}

	@Override
	public void shutdown() {
		log.warn(name + ": shutting down");
		scopeMap.forEach((String s,TTLObject<T> o)->{
			try{if(o!=null&&o.getTheObject()!=null)
				dispose(o.getTheObject());
			}catch(Throwable t) {
				log.warn(name +": unable to dispose ",t);
			}
		});
	}

}
