package br.com.bancooriginal.cyberbank.awt.validators;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextField;

/**
 * Validador de Strings
 * @author filipe.sa
 *
 */
public class StringVerifier extends InputVerifier implements ActionListener{

	private int qtdCaracteres;
	private boolean obrigatorio;
	private JLabel validationLabel;
	
	/**
	 * Contrutor que recebe a quantidade de caracteres possiveis
	 * para o campo de input, alem de receber um boleano que indica se o campo eh obrigatorio
	 * ou nao.
	 * @param qtdCaracteres
	 * @param obrigatorio
	 */
	public StringVerifier(int qtdCaracteres, boolean obrigatorio, JLabel validationLabel){
		this.validationLabel=validationLabel;
		this.qtdCaracteres=qtdCaracteres;
		this.obrigatorio=obrigatorio;
	}

	@Override
	public boolean verify(JComponent input) {
		
		JTextField textField = ((JTextField) input);
		
		if(obrigatorio && (null == textField.getText() || "".equals(textField.getText().trim()))){
			textField.setBackground(Color.RED);
			if(null != validationLabel){
				validationLabel.setText("Campo obrigatório");
			}
			return false;
		}
		
		if(textField.getText().length() > qtdCaracteres){
			textField.setBackground(Color.RED);
			if(null != validationLabel){
				validationLabel.setText("Valor inválido. Máximo de "+qtdCaracteres+" caracteres.");
			}
			return false;
		}
		
		textField.setBackground(Color.WHITE);
		if(null != validationLabel){
			validationLabel.setText("");
		}
		return true;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		JTextField source = (JTextField)e.getSource();
        shouldYieldFocus(source);
        source.selectAll();
		
	}

}
