package eu.dnetlib.data.collective.manager.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import edu.emory.mathcs.backport.java.util.Collections;
import eu.dnetlib.data.collective.manager.profile.AbstractInstance;

/**
 * @author jochen
 *
 * @param <T> type of the instance data structure
 */
@SuppressWarnings("unchecked")
public class InstanceRegistry<T extends AbstractInstance> {

	protected Map<String, T> instanceMap = Collections.synchronizedMap(new HashMap<String, T>());

	/**
	 * @return a list of all managed instance datastructures
	 */
	public List<T> getInstanceList() {
		List<T> l = new Vector<T>();
		l.addAll(instanceMap.values());
		return l;
	}

	/**
	 * @param instances - map with resourceProfileId as keys and Instance Datastructure as value
	 */
	protected void setInstances(Map<String, T> instances) {
		instanceMap = instances;
	}
	
	/**
	 * Gets the instance with the given id
	 * @param id the resource profile id
	 * @return the instance
	 */
	public T getInstance(String id){
		return instanceMap.get(id);
	}
	
	/**
	 * Removes the instance with given id from the registry
	 * @param id the resource profile id
	 */
	public void removeInstance(String id){
		instanceMap.remove(id);
	}
	
	/**
	 * Checks if instance with given id is registered
	 * @param id the resource profile id
	 * @return true, if id is registered else false
	 */
	public boolean containsInstance(String id){
		return instanceMap.containsKey(id);
	}
	
	/**
	 * Adds the instance with the given id to the registry
	 * @param id the resource profile id
	 * @param instance the instance of the resource profile with the given id
	 */
	public void addInstance(String id, T instance){
		instanceMap.put(id, instance);
	}
	
	/**
	 * Updates the registry with the given id and instance
	 * @param id the resource profile id
	 * @param instance the instance of the resource profile with given id
	 * @return true if updated else false
	 */
	public boolean updateInstance(String id, T instance){
		if (containsInstance(id)){
			instanceMap.put(id, instance);
			return true;
		}
		return false;
	}

}
