package de.ivu.elect.jee.memory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

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

@ApplicationScoped
public class MemoryGcStore implements Serializable {

  private static final long MAX_ITERATIONS = 1000;

  private final ConcurrentLinkedQueue<MemoryGcData> data = new ConcurrentLinkedQueue<>();

  @Inject
  private transient MemoryGcKonfiguration memoryGcKonfiguration;

  public void add(MemoryGcData memoryGcData) {
    if (data.isEmpty()) {
      data.add(memoryGcData); // ersten Eintrag doppelt speichern für offest bei GC-Werten
    }
    data.add(memoryGcData);
    strip(data, memoryGcKonfiguration.getMaximaleAnzahlEintraege());
  }

  static void strip(ConcurrentLinkedQueue<MemoryGcData> data, long maximaleAnzahlEintraege) {
    if (maximaleAnzahlEintraege > 0) {
      long count = 0; // Endlosschleife mal vermeiden....
      while (count < MAX_ITERATIONS && data.size() > maximaleAnzahlEintraege) {
        count++;
        data.poll();
      }
    }

  }

  public List<MemoryGcData> getData() {
    return new ArrayList<>(data);
  }

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

}
