package com.rjconsultores.ventaboletos.utilerias.seguridad;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Pattern;

import com.rjconsultores.ventaboletos.exception.BusinessException;

public class ContrasenaUtileria {
	private int CANT_MIN_CARACTER = 6;
	private int CANT_MIN_NUMERO = 1;
	private int CANT_MIN_LETRA = 1;
	private int CANT_ESPECIALES = 0;

	private Pattern patternHayNumero = null;
	private Pattern patternHayLetra = null;
	private Pattern patternHayEspeciales = null;

	public ContrasenaUtileria(){
		this.cargarPattern();
	}
	
	public ContrasenaUtileria(int cantMinCaracteres){
		CANT_MIN_CARACTER = cantMinCaracteres;
		this.cargarPattern();
	}
	
	private void cargarPattern(){
		patternHayNumero = Pattern.compile(String.format(".*[0-9]{%s,}+.*",CANT_MIN_NUMERO));
		patternHayLetra = Pattern.compile(String.format(".*[a-zA-Z]{%s,}+.*",CANT_MIN_LETRA));
		patternHayEspeciales = Pattern.compile(String.format("((.*[\\W]){%s,})",CANT_ESPECIALES));
		
	}
	
	public ContrasenaUtileria(int cantMinCaracteres,int cantMinNumeros,int cantMinLetra,int cantEspeciales){
		CANT_ESPECIALES = cantEspeciales;
		CANT_MIN_CARACTER = cantMinCaracteres;
		CANT_MIN_LETRA = cantMinLetra;
		CANT_MIN_NUMERO = cantMinNumeros;
		
		this.cargarPattern();
	}
	
	public static String encriptarContrasena(String contrasena){
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		
		byte[] pass = md.digest(contrasena.getBytes());
		return  Base64.byteArrayToBase64(pass);
	}
	public void validarContrasenaCompleja(String contrasena) throws BusinessException{
		int length = contrasena.length();
		
		if (length< CANT_MIN_CARACTER){
			throw new BusinessException("complejidadContrasena.CANT_MIN_CARACTER", new Object[]{CANT_MIN_CARACTER});
		}
				
		if (!patternHayLetra.matcher(contrasena).find()){
			throw new BusinessException("complejidadContrasena.CANT_MIN_LETRA", new Object[]{CANT_MIN_LETRA});
		}
		
		if (!patternHayNumero.matcher(contrasena).find()){
			throw new BusinessException("complejidadContrasena.CANT_MIN_NUMERO", new Object[]{CANT_MIN_NUMERO});
		}
		
		if (!patternHayEspeciales.matcher(contrasena).find()){
			throw new BusinessException("complejidadContrasena.CANT_ESPECIALES", new Object[]{CANT_ESPECIALES});
		}
	}


}
