package ru.yandex.canvas.model.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class DifferentlyColoredOptionsValidator
        implements ConstraintValidator<DifferentlyColoredOptions, Element.ColoredTextOptionsWithBackground> {

    private static final Logger logger = LoggerFactory.getLogger(DifferentlyColoredOptionsValidator.class);

    private double distance;
    private DifferentlyColoredOptions.Metric metric;

    @Override
    public void initialize(DifferentlyColoredOptions constraint) {
        this.distance = constraint.distance();
        this.metric = constraint.metric();
    }


    @Override
    public boolean isValid(Element.ColoredTextOptionsWithBackground options, ConstraintValidatorContext context) {
        boolean isValid;
        try {
            isValid = !metric.almostTheSameColors(options.getBackgroundColor(), options.getColor(), distance);
        } catch (NumberFormatException e) {
            logger.warn("can't compute color difference", e);
            isValid = true;
        }

        if (!isValid) {
            context.disableDefaultConstraintViolation();

            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode("color").addConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode("backgroundColor").addConstraintViolation();
        }
        return isValid;
    }
}
