package de.ivu.elect.presentation.system;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Nullable;
import javax.transaction.Synchronization;

import de.ivu.elect.presentation.system.table.DAOCacheFinderKey;

public class DAOCacheContent implements Synchronization {

  private final Object transactionKey;

  private final Map<DAOCacheFinderKey, SoftReference<Object>> cache = new HashMap<>();

  public DAOCacheContent(Object transactionKey) {
    this.transactionKey = transactionKey;
  }

  public void put(FinderKey finderKey, Object object) {
    if (object!=null) {
      cache.put(new DAOCacheFinderKey(finderKey), new SoftReference<>(object));
    }
  }

  @Nullable
  public Object lookup(FinderKey finderKey) {
    SoftReference<Object> objectSoftReference = cache.get(new DAOCacheFinderKey(finderKey));
    if (objectSoftReference == null) {
      return null;
    }
    return objectSoftReference.get();
  }

  public void clear() {
    cache.clear();
  }

  public Object getTransactionKey() {
    return transactionKey;
  }

  @Override
  public void beforeCompletion() {
    clear();
  }

  @Override
  public void afterCompletion(int status) {
    clear();
  }
}
