package com.ease.gsms.server.model.util;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

public class E164NumberValidator implements ConstraintValidator<ValidE164Number, String> {

    private final ThreadLocal<Pattern> pattern = ThreadLocal.withInitial(() -> Pattern.compile("^\\+[0-9]{10,14}$"));

    @Override
    public void initialize(ValidE164Number constraintAnnotation) {
    }

    @Override
    public boolean isValid(String phoneNumberString, ConstraintValidatorContext constraintValidatorContext) {
        PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
        try {
            return phoneNumberString == null || (pattern.get().matcher(phoneNumberString).matches() && phoneNumberUtil.isPossibleNumber(phoneNumberUtil.parse(phoneNumberString, "RO")));
        } catch (NumberParseException e) {
            return false;
        }
    }
}
