package ru.yandex.qe.dispenser.quartz.monitoring;

import java.util.BitSet;

public class JobFailuresAggregator {

    private final BitSet jobResults;
    private final int windowSize;

    private int samples;
    private int pointer;

    public JobFailuresAggregator(final int windowSize) {
        if (windowSize <= 0) {
            throw new IllegalArgumentException("Window size must be positive");
        }
        jobResults = new BitSet(windowSize);
        this.windowSize = windowSize;
        this.samples = 0;
        this.pointer = 0;
    }

    public synchronized void aggregate(final boolean failure) {
        if (samples < windowSize) {
            samples++;
        }
        jobResults.set(pointer, failure);
        pointer++;
        if (pointer >= windowSize) {
            pointer = 0;
        }
    }

    public synchronized double failureRatio() {
        // Take ratio to full window size to avoid false alarms right after bootstrap
        return (double) jobResults.cardinality() / windowSize;
    }
}
