package ru.yandex.canvas.model.validation.presetbased.elements;

import javax.annotation.Nonnull;

import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.validation.Errors;

import ru.yandex.canvas.model.elements.Element;

/**
 * Validates that string is either `null`, empty, or contains at least one non-whitespace symbol
 */
public class NotWhitespaceValidator extends ElementValidator<Element> {

    private static final String MESSAGE = "{org.hibernate.validator.constraints.NotBlank.message}";

    /**
     * Имя поля, которое будет в ошибке валидации.
     * Нужно, например, для ageRestiction, там используется value вместо content
     * @see ru.yandex.canvas.model.elements.AgeRestriction.Options
     */
    @Nonnull
    private String fieldName = "content";

    public NotWhitespaceValidator() {
    }

    public NotWhitespaceValidator(@Nonnull String fieldName) {
        this.fieldName = fieldName;
    }

    public void setFieldName(@Nonnull String fieldName) {
        this.fieldName = fieldName;
    }

    @Override
    public boolean isSupported(Element element) {
        return element != null && element.getAvailable() && element.getOptions() instanceof Element.ColoredTextOptions;
    }

    @Override
    public void validate(Element element, @NonNull Errors errors) {
        Element.ColoredTextOptions options = ((Element.ColoredTextOptions) element.getOptions());

        if (!isValid(options.getContent())) {
            errors.rejectValue("options." + fieldName, "content.is.whitespace", MESSAGE);
        }
    }

    public static boolean isValid(String content) {
        return content == null || content.isEmpty() || !content.trim().isEmpty();
    }
}
