package com.atlassian.stash.internal.validation;

import com.atlassian.bitbucket.server.ApplicationMode;
import com.atlassian.bitbucket.server.ApplicationModeSupplier;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

/**
 * Validator that validates that the annotated field/method is null in all of the modes marked as unsupported
 */
public class UnsupportedInApplicationModeValidator implements ConstraintValidator<UnsupportedInApplicationMode, Object> {

    private ApplicationModeSupplier applicationModeSupplier;
    private ApplicationMode[] unsupportedModes;

    @Override
    public void initialize(UnsupportedInApplicationMode constraintAnnotation) {
        unsupportedModes = constraintAnnotation.applicationMode();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return value == null || Arrays.stream(unsupportedModes).noneMatch(mode -> mode == applicationModeSupplier.getMode());
    }

    @Autowired
    public void setApplicationModeSupplier(ApplicationModeSupplier applicationModeSupplier) {
        this.applicationModeSupplier = applicationModeSupplier;
    }
}

