package com.fp.frontend.validators;

import java.math.BigDecimal;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.fp.frontend.utility.ValidateIdentification;

@FacesValidator(value = "cedulaValidator")
public class CedulaValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value)
            throws ValidatorException {

        try {
            if (value.toString().length() != 10 || !ValidateIdentification.cedula(value.toString())) {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "El n\u00famero ingresado no es v\u00e1lido. Por favor verificar", "El n\u00famero ingresado no es v\u00e1lido. Por favor verificar."));
            }
        } catch (Throwable e) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
        }

    }

    public static boolean validarCedula(String id) {

        boolean result = true;

        int[] modulo9 = {2, 1, 2, 1, 2, 1, 2, 1, 2};

        BigDecimal verif = BigDecimal.ZERO;
        if (id.length() != 10) {
            result = false;
        } else {
            for (int i = 0; i < 9; i++) {
                BigDecimal temp = new BigDecimal(new BigDecimal(id.substring(i, (i + 1))).multiply(new BigDecimal(modulo9[i])).toString());
                if (temp.doubleValue() > 9) {
                    temp = temp.subtract(new BigDecimal("9"));
                }
                verif = verif.add(temp);
            }
            if (verif.doubleValue() % 10 == 0) {
                if (Integer.parseInt(id.substring(9, 10)) == 0) {
                    result = true;
                } else {
                    result = false;
                }
            } else if ((10 - (verif.doubleValue() % 10)) == Integer.parseInt(id.substring(9, 10))) {
                result = true;
            } else {
                result = false;
            }
        }
        return result;
    }

}
