package de.ivu.elect.business.personenregister.control;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.business.konfiguration.entity.KonfigurationNewTransaktionLoader;
import de.ivu.elect.business.konfiguration.entity.MandantKonfigurationWerte;
import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.mandant.entity.MandantPK;

public class PersonenregisterCacheResolver {

  @Inject
  private transient KonfigurationNewTransaktionLoader konfigurationLoader;

  private static final Logger LOG = LoggerFactory.getLogger(PersonenregisterCacheResolver.class);

  private static final Map<MandantPK, PersonenRegisterCache> mandantPKPersonenRegisterCacheMap = new ConcurrentHashMap<>();

  public PersonenRegisterCache getPersonenRegisterCache(Mandant mandant) {
    if (mandant == null || mandant.getPk() == null) {
      return new NoopPersonenRegisterCache();
    }

    return mandantPKPersonenRegisterCacheMap.computeIfAbsent(mandant.getPk(), x -> createPersonenregisterCache(mandant));
  }

  public void reset(Mandant mandant) {
    if (mandant != null && mandant.getPk() != null) {
      if (mandantPKPersonenRegisterCacheMap.remove(mandant.getPk()) != null) {
        LOG.info("Cache reset: " + mandant);
      }
    }
  }

  private PersonenRegisterCache createPersonenregisterCache(Mandant mandant) {
    Long cacheSize = konfigurationLoader.resolveLongValueOptional(mandant, MandantKonfigurationWerte.PERSONENREGISTER_CACHE_SIZE);
    if (cacheSize == null || cacheSize < 1) {
      LOG.info("Noop-Cache created: " + mandant);
      return new NoopPersonenRegisterCache();
    }
    LOG.info("Cache created: " + mandant + ", " + cacheSize);
    return new LruPersonenRegisterCache(mandant.getPk(), cacheSize);
  }

}
