package alien4cloud.plugin.marathon.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import alien4cloud.paas.model.AbstractMonitorEvent;

/**
 * @author Adrian Fraisse
 */
class EventCache {

    private long lastAccessed;
    private List<AbstractMonitorEvent> events = Collections.synchronizedList(new ArrayList<>());

    public EventCache(final long cacheCleanupInterval) {

        if (cacheCleanupInterval > 0) Executors.newSingleThreadExecutor().submit(() -> {
            while (true) {
                Thread.sleep(cacheCleanupInterval * 1000);
                cleanUp();
            }
        });
    }

    // TODO: leverage the fact that the event list is always sorted
    private void cleanUp() {
        synchronized (events) {
            events = events.stream()
                        .filter(event -> event.getDate() < lastAccessed)
                        .collect(Collectors.toList());
        }
    }

    protected List<AbstractMonitorEvent> getEventsSince(long date, int batchSize) {
        synchronized (events) {
            List<AbstractMonitorEvent> subList =
                    events.stream().filter(event -> event.getDate() > date).limit(batchSize).collect(Collectors.toList());
            this.lastAccessed = date;
            return subList;
        }
    }

    protected void pushEvent(AbstractMonitorEvent event) {
        synchronized (events) {
            events.add(event);
        }
    }
}

@@ -253,16 +253,99 @@
 t;%0A%0A/**%0A
+ * A cache to store events from Marathon.%0A * The cache is periodically cleaned.%0A *%0A
  * @auth
@@ -429,16 +429,22 @@
 private 
+final 
 List%3CAbs
@@ -529,15 +529,8 @@
     
-public 
 Even
@@ -948,22 +948,56 @@
         
-events
+final List%3CAbstractMonitorEvent%3E collect
  = event
@@ -1007,20 +1007,16 @@
 tream()%0A
-    
         
@@ -1096,20 +1096,16 @@
         
-    
 .collect
@@ -1135,38 +1135,92 @@
         
-%7D%0A
     
-%7D%0A%0A    protected
+events.clear();%0A            events.addAll(collect);%0A        %7D%0A    %7D%0A%0A   
  List%3CAb
@@ -1577,18 +1577,8 @@
     
-protected 
 void

Make event list final