package org.jboss.installer.validators;

import org.jboss.installer.core.ValidationResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Executes multiple validators. The execution is performed in order of {@code validators}.
 * If any validator fails, the error is reported, and subsequent validators are not executed.
 * If a validator returns a warning, remaining validators are executed. If any of the remaining validators fail,
 * the failure is reported, otherwise the warning is reported.
 * If more than one validator returns a warning, the first warning is used.
 */
public class CombiningValidator implements Validator {
    private final List<Validator> validators;

    private CombiningValidator(List<Validator> validators) {
        this.validators = validators;
    }

    public static CombiningValidator of(Validator... validators) {
        Objects.requireNonNull(validators);

        return new CombiningValidator(List.of(validators));
    }

    public static CombiningValidator of(List<Validator> validators) {
        Objects.requireNonNull(validators);

        return new CombiningValidator(validators);
    }

    @Override
    public ValidationResult validate() {
        final List<ValidationResult> warnings = new ArrayList<>();

        for (Validator validator : validators) {
            final ValidationResult result = validator.validate();
            if (result.getResult() == ValidationResult.Result.ERROR) {
                return result;
            } else if (result.getResult() == ValidationResult.Result.WARNING) {
                warnings.add(result);
            }
        }
        if (warnings.isEmpty()) {
            return ValidationResult.ok();
        } else {
            return ValidationResult.warning(warnings.stream().flatMap(r->r.getMessages().stream()).collect(Collectors.toList()));
        }
    }
}
