package me.qwq.doghouse.validator;

import java.util.regex.Pattern;

import org.springframework.stereotype.Component;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import me.qwq.doghouse.interfaces.IFriendlyName;

@Component
public class FriendlyNameValidator implements IValidator, ConstraintValidator<FriendlyNameValid, IFriendlyName> {

    static final ForbiddenPattern[] FORBIDDEN_PATTERNS = {
            new ForbiddenPattern("/"),
            new ForbiddenPattern("\\\\", "友好名称或页面名称不允许包含字符串\"\\\""),
    }; 
    
    @Override
    public boolean isValid(IFriendlyName value, ConstraintValidatorContext context) {
        String friendlyName = value.getFriendlyName();
        if (friendlyName == null) return true;
        
        for (ForbiddenPattern p : FORBIDDEN_PATTERNS) {
            if (p.pattern.matcher(friendlyName).find()) {
                return invalid(context, new StringBuilder(value.getClass().getSimpleName())
                        .append(' ').append(p.message).toString());
            }
        }
        
        return true;
    }
    
    private static class ForbiddenPattern {
        protected Pattern pattern;
        protected String message;

        protected ForbiddenPattern(String regex, String message) {
            this.pattern = Pattern.compile(regex);
            this.message = message;
        }
        
        protected ForbiddenPattern(String regex) {
            this(regex, "友好名称或页面名称不允许包含字符串\"" + regex.replace("\\", "") + "\"");
        }
    }

}
