package cz.senslog.analytics.utils.validator;

import cz.senslog.analytics.domain.AttributeName;
import cz.senslog.analytics.domain.ValidationResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InstantNotifyTrigger implements NotifyTrigger {

    private final Map<AttributeName, ValidationResult> currentResultMap;
    private List<AttributeName> tempAttrsToNotify;

    public InstantNotifyTrigger() {
        this.currentResultMap = new HashMap<>();
    }

    @Override
    public void accept(ValidationResult validationResult) {
        currentResultMap.put(validationResult.attribute(), validationResult);
    }

    @Override
    public boolean shouldNotify() {
        boolean notify = false;
        tempAttrsToNotify = new ArrayList<>();
        for (ValidationResult res : currentResultMap.values()) {
            if (res.isNotValid()) {
                notify = true;
                tempAttrsToNotify.add(res.attribute());
            }
        }
        return notify;
    }

    @Override
    public ValidationResult[] resultsToNotify() {
        ValidationResult[] res = new ValidationResult[tempAttrsToNotify.size()];
        int ind = 0;
        for (AttributeName attr : tempAttrsToNotify) {
            res[ind++] = currentResultMap.get(attr);
        }
        tempAttrsToNotify = null;
        return res;
    }
}
