
package de.ivu.elect.presentation.system;

import javax.annotation.PreDestroy;
import javax.enterprise.context.RequestScoped;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RequestScoped
public class ExtendedDAORequestCache implements Serializable {

  private static final long serialVersionUID = 1L;

  // ELECT-6734 NPE beim Einfügen von NULL-Werten in ConcurrentHashMap
  private static final Object NULL_VALUE = new Object();

  private Map<FinderKey, Object> cache;

  private Map<FinderKey, Object> getCache() {
    if (cache == null) {
      cache = new ConcurrentHashMap<>();
    }
    return cache;
  }

  @PreDestroy
  public void destroy() {
    cache = null;
  }

  public boolean contains(FinderKey key) {
    return cache != null && getCache().containsKey(key);
  }

  public Object lookup(FinderKey key) {
    Object result = getCache().get(key);
    if (NULL_VALUE.equals(result)){
      return null;
    }
    return result;
  }

  public <T> T put(FinderKey key, T result) {
    if (result==null) {
      getCache().put(key, NULL_VALUE);
    } else {
      getCache().put(key, result);
    }

    return result;
  }

  public void clear() {
    cache = null;
  }
}
