package cz.senslog.analytics.utils.validator;

import cz.senslog.analytics.domain.AttributeType;
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<AttributeType, ValidationResult> currentResultMap;
    private List<AttributeType> tempAttrsToNotify;

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

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

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

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