package com.airlock.iam.saml2.domain.model;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.time.Duration;
import java.util.Optional;
import org.apache.commons.lang3.Validate;

public final class InMemoryCache<K, V> {
   private static final Duration ENTRY_EXPIRATION = Duration.ofMinutes(2L);
   private final Cache<K, V> cache = CacheBuilder.newBuilder().expireAfterWrite(ENTRY_EXPIRATION).build();

   public K put(K key, V value) {
      Validate.isTrue(this.cache.getIfPresent(key) == null, "There is already an entry under the key " + key, new Object[0]);
      this.cache.put(key, value);
      return key;
   }

   public Optional<V> read(K key) {
      return Optional.ofNullable((V)this.cache.getIfPresent(key));
   }

   public void remove(K key) {
      this.cache.invalidate(key);
   }

   public Optional<V> readOnce(K key) {
      Optional<V> data = this.read(key);
      this.remove(key);
      return data;
   }

   public void clear() {
      this.cache.invalidateAll();
      this.cache.cleanUp();
   }
}
