package utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator(value = "rutValidator")
public class RutValidator implements Validator {

  private final static Pattern PATTERN = Pattern.compile("(\\d+)-(\\d|k)", Pattern.CASE_INSENSITIVE);

  @Override
  public void validate(FacesContext fc, UIComponent uic, Object o) throws ValidatorException {
    Matcher matcher = PATTERN.matcher(o.toString());

    if (!matcher.matches()) {
      FacesMessage message = new FacesMessage("Rut: El formato no es correcto");
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ValidatorException(message);
    }

    if (!rutChecksum(matcher.group(1), matcher.group(2).toLowerCase().charAt(0))) {
      FacesMessage message = new FacesMessage("Rut: El digito verificador no es correcto");
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ValidatorException(message);
    }

  }

  private boolean rutChecksum(String body, char dv) {
    int sum = 0;
    for (int i = body.length() - 1, j = 2; i >= 0; i--, j++) {
      int digit = body.charAt(i) - '0';
      if (j == 8)
        j = 2;

      sum += digit * j;
    }

    int mod11 = 11 - (sum % 11);

    char digitoVerificador = (char) (mod11 + '0');
    if (mod11 == 11)
      digitoVerificador = '0';
    if (mod11 == 10)
      digitoVerificador = 'k';
    
    return dv == digitoVerificador ;
  }
}
