/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.elotech.websaude.integracao.cnes.backend.util;

/**
 *
 * @author usuario
 */
public class Ibge {
    public static String valida(String codigo) {

        if(codigo.length()==7)
            return codigo;
        int i;
        int valor;
        int soma;
        String result;
        String digito;
        final String PESO = "1212120";
        final String NAO_VALIDAR = "|2201919|2202251|2201988|2611533|3117836|3152131|4305871|5203939|5203962|";

        if (codigo.length() < 6) {
            result = "Tamanho Inválido";
        }
        if (NAO_VALIDAR.contains("|" + codigo.substring(0, 6))) {
            String[] nao = NAO_VALIDAR.split("\\|");
            for (int j = 0; j < nao.length; j++) {
                if (nao[j].contains(codigo)) {
                    result = nao[j];
                    return result;
                }
            }
        }

        soma = 0;

        for (int j = 0; j < 6; j++) {
            valor = Integer.valueOf(codigo.substring(j, j + 1)) * Integer.valueOf(PESO.substring(j, j + 1));
            if (valor > 9) {
                soma = soma
                        + Integer.valueOf((valor + "").substring(0, 1))
                        + Integer.valueOf((valor + "").substring(1, 2));
            } else {
                soma = soma + valor;
            }
        }
        digito = ((10 - (soma % 10))) + "";
        if ((soma % 10) == 0) {
            digito = "0";
        }
        result = codigo.substring(0, 6) + digito;
        return result;
    }
}
