package cz.senslog.analytics.module.api;

import cz.senslog.analytics.domain.AnalyticGroup;
import cz.senslog.analytics.domain.DoubleStatistics;
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 AnalyticGroup analyticGroup;
    private final OffsetDateTime startTime, endTime;
    private final Map<Long, DoubleStatistics> statistics;

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

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

    public OffsetDateTime startTime() {
        return startTime;
    }

    public OffsetDateTime endTime() {
        return endTime;
    }

    public AnalyticGroup group() {
        return analyticGroup;
    }

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

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

    public boolean readyToProcess() {
        return false;
    }
}