package com.krillsson.sysapi.core.history;

import com.google.common.annotations.VisibleForTesting;
import com.krillsson.sysapi.util.TimeMachine;
import org.slf4j.Logger;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

public class History<T> {
    private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(History.class);

    private final List<HistoryEntry<T>> history;
    private final TimeMachine timeMachine;

    protected History() {
        this(new TimeMachine());
    }

    @VisibleForTesting
    protected History(TimeMachine timeMachine) {
        this.timeMachine = timeMachine;
        this.history = new ArrayList<>();
    }

    public List<HistoryEntry<T>> get() {
        return Collections.unmodifiableList(history);
    }

    public void record(T value) {
        LOGGER.trace("Recording history for {}", value.getClass().getSimpleName());
        history.add(new HistoryEntry<>(timeMachine.now(/* with system timezone */), value));
    }

    public void purge(int olderThan, ChronoUnit unit) {
        LocalDateTime maxAge = timeMachine.now().minus(olderThan, unit);
        Set<HistoryEntry> toBeRemoved = new HashSet<>();
        for (HistoryEntry historyEntry : history) {
            if (historyEntry.date.isBefore(maxAge)) {
                toBeRemoved.add(historyEntry);
            }
        }

        LOGGER.trace("Purging {} entries older than {} {}", toBeRemoved.size(), olderThan, unit.name());
        toBeRemoved.forEach(history::remove);
    }
}

@@ -126,27 +126,21 @@
 pi.util.
-TimeMachine
+Clock
 ;%0Aimport
@@ -435,39 +435,27 @@
 e final 
-TimeMachine timeMachine
+Clock clock
 ;%0A%0A    p
@@ -492,27 +492,21 @@
 his(new 
-TimeMachine
+Clock
 ());%0A   
@@ -558,73 +558,49 @@
 ory(
-TimeMachine timeMachine) %7B%0A        this.timeMachine = timeMachine
+Clock clock) %7B%0A        this.clock = clock
 ;%0A  
@@ -905,27 +905,21 @@
 Entry%3C%3E(
-timeMachine
+clock
 .now(/* 
@@ -1051,19 +1051,13 @@
 e = 
-timeMachine
+clock
 .now

Rename TimeMachine -> Clock