package cz.senslog.analytics.module.api;

import cz.senslog.analytics.domain.DoubleStatistics;
import cz.senslog.analytics.domain.Group;
import cz.senslog.analytics.domain.Sensor;
import cz.senslog.analytics.utils.DateTrunc;

import java.time.OffsetDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


public class CollectedStatistics {

    private final Group group;
    private final OffsetDateTime startTime, endTime;
    private final Map<Long, DoubleStatistics> statistics;

    public static CollectedStatistics init(Group group, OffsetDateTime timestamp) {
        return new CollectedStatistics(group, DateTrunc.trunc(timestamp, group.interval()));
    }

    private CollectedStatistics(Group group, OffsetDateTime startTime) {
        this.group = group;
        this.startTime = startTime;
        this.endTime = startTime.plusSeconds(group.interval());
        this.statistics = new HashMap<>();
    }

    public OffsetDateTime startTime() {
        return startTime;
    }

    public OffsetDateTime endTime() {
        return endTime;
    }

    public Group group() {
        return group;
    }

    public Collection<DoubleStatistics> statistics() {
        return statistics.values();
    }

    public DoubleStatistics accept(Sensor source, double value) {
        long sourceId = source.groupId();
        DoubleStatistics st = statistics.computeIfAbsent(sourceId, s -> DoubleStatistics.init(s, startTime));
        st.accept(sourceId, value);
        return st;
    }

    public boolean readyToProcess() {
        return false;
    }
}