package sac.pessoa.util;

import java.math.BigInteger;

/**
 *  Classe que verifica se um cpf é valido ou não
 */

public class HandlerCPF implements HandlerString{

  /**
   *  Metodo que indica se um determinado CPF é valido ou não.
   *
   * @param CPF <code>String</code> a ser validada.
   * @return <code>boolean</code> indicando se o CPF válido. Sendo <code>true</code>
   *    se o CPF for válido, caso contrário o método retornara <code>false</code>.
   */
  public  boolean valida ( String CPF){
    try{
      return ( CPF == null)? false : isValidCPF(CPF);
    } catch (NumberFormatException nfe){
      return false;
    }
  }

  private  boolean isValidCPF(String CPF) throws NumberFormatException{
    if (CPF.length() != 11 || CPF == "00000000000" || CPF == "11111111111" ||
    CPF == "22222222222" || CPF == "33333333333" || CPF == "44444444444" ||
    CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
    CPF == "88888888888" || CPF == "99999999999")
    {
      return false;
    }
    int resto=0 , soma = 0;
    for (int i=0; i < 9; i ++) {
      soma += parseInt(CPF.charAt(i)) * (10 - i);
    }
    resto = 11 - (soma % 11);
    if (resto == 10 || resto == 11) {
        resto = 0;
    }
    if (resto != parseInt(CPF.charAt(9))){
        return false;
    }
    soma = 0;
    for (int i = 0; i < 10; i ++)
      soma += parseInt(CPF.charAt(i)) * (11 - i);
    resto = 11 - (soma % 11);
    if (resto == 10 || resto == 11)
    resto = 0;

    if (resto != parseInt(CPF.charAt(10))){
      return false;
    }
    return true;
  }
  private int parseInt(char c ){
    if ( Character.isDigit(c))
      return Character.getNumericValue(c);
    else {
      throw new NumberFormatException();
    }
  }

  /**
   *
   */
  public static void main(String[] args) {
    HandlerCPF h = new HandlerCPF();
    System.out.println(  h.valida("03359920481"));
    System.out.println(  h.valida("02969716429"));
    System.out.println(  h.valida("02969712429"));
    System.out.println(  h.valida("0296971a429"));
    System.out.println(  h.valida("00000000000"));
  }
}