package com.eactive.httpmockserver.common.validator;

import com.eactive.httpmockserver.common.util.ApplicationContextUtil;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

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

public class PasswordMatchValidator implements ConstraintValidator<PasswordMatch, Object> {

    private String field1;
    private String field2;

    @Override
    public void initialize(PasswordMatch constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.field1 = constraintAnnotation.input();
        this.field2 = constraintAnnotation.confirm();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        Object passwordValue = null;
        Object password2Value = null;

        try {
            passwordValue = PropertyUtils.getProperty(value, field1);
            password2Value = PropertyUtils.getProperty(value, field2);
        } catch (Exception e) {
            return false;
        }
        if (Objects.isNull(passwordValue) || Objects.isNull(password2Value)) {
            return false;
        }

        MessageSource messageSource = (MessageSource) ApplicationContextUtil.getContext().getBean("messageSource");
        String message = messageSource.getMessage("password.not.match", null, LocaleContextHolder.getLocale());

        if (!passwordValue.equals(password2Value)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message)
                    .addPropertyNode(field2)
                    .addConstraintViolation();
            return false;
        }
        return true;
    }
}
