package de.ugoe.cs.eventbench.data;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class GlobalDataContainer implements Serializable {
	
	/**
	 * Id for object serialization.
	 */
	private static final long serialVersionUID = 1L;

	transient private static GlobalDataContainer theInstance = null;
	
	private Map<String, Object> dataObjects;
	
	public static GlobalDataContainer getInstance() {
		if( theInstance==null ) {
			theInstance = new GlobalDataContainer();
		}
		return theInstance;
	}
	
	private void writeObject(ObjectOutputStream s) throws IOException {
		s.defaultWriteObject();
		s.writeObject(dataObjects);
	}
	
	@SuppressWarnings("unchecked")
	private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
		s.defaultReadObject();
		if( theInstance==null ) {
			theInstance = new GlobalDataContainer();
		}
		theInstance.dataObjects = (Map<String, Object>) s.readObject();
	}
	
	private Object readResolve() {
		return theInstance;
	}
	
	private GlobalDataContainer() {
		dataObjects = new HashMap<String, Object>();
	}
	
	public boolean addData(String key, Object data) {
		Object previousEntry = dataObjects.put(key, data);
		return previousEntry!=null;
	}
	
	public boolean removeData(String key) {
		Object previousEntry = dataObjects.remove(key);
		return previousEntry==null;
	}
	
	public Object getData(String key) {
		return dataObjects.get(key);
	}
	
	public void reset() {
		dataObjects = new HashMap<String, Object>();
	}

}
