package com.eactive.httpmockserver.common.validator;

import com.eactive.httpmockserver.api.repository.MockRouteRepository;
import com.eactive.httpmockserver.common.exception.UserNotFoundException;
import com.eactive.httpmockserver.common.util.ApplicationContextUtil;
import com.eactive.httpmockserver.user.service.UserService;
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;

public class UniqueRouteValidator implements ConstraintValidator<UniqueRoute, Object> {

    private String method;

    private String path;

    @Override
    public void initialize(UniqueRoute constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.method = constraintAnnotation.method();
        this.path = constraintAnnotation.path();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        String methodValue;
        String pathValue;
        try {
            methodValue = (String) PropertyUtils.getProperty(value, this.method);
            pathValue = (String) PropertyUtils.getProperty(value, this.path);
        } catch (Exception e) {
            return false;
        }
        MockRouteRepository mockRouteRepository = ApplicationContextUtil.getContext().getBean(MockRouteRepository.class);
        long found = mockRouteRepository.countByMethodAndPathPattern(methodValue, pathValue);

        String message = "등록된 API가 존재합니다.";

        if (found > 0L){
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message)
                    .addPropertyNode(this.path)
                    .addConstraintViolation();

            return false;
        }

        return true;
    }
}
