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

import java.util.regex.Pattern;

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

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

public class ValidColorValidator extends ElementValidator<Element> {

    public static final String MESSAGE = "{invalid_color_value}";

    public static final String COLOR_PATTERN = "#[0-9A-Fa-f]{6}";

    public ValidColorValidator() {
    }

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

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

        checkColor(options.getColor(), "options.color", errors);

        if (options instanceof Element.ColoredTextOptionsWithBackground) {
            String backgroundColor = ((Element.ColoredTextOptionsWithBackground) options).getBackgroundColor();

            checkColor(backgroundColor, "options.backgroundColor", errors);
        }

        if (options instanceof Legal.Options) {
            String iconColor = ((Legal.Options) options).getIconColor();

            checkColor(iconColor, "options.iconColor", errors);
        }
    }

    public static void checkColor(String color, String fieldName, Errors errors) {
        if (color != null && !Pattern.matches(COLOR_PATTERN, color)) {
            errors.rejectValue(fieldName, "color.is.invalid", MESSAGE);
        }
    }
}
