package componentes;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class JTextFieldPrazo extends PlainDocument {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8020852662258513751L;
	private int iMaxLength;
	private JTextField txt;
	private long num;
	
	public JTextFieldPrazo(int pMaxLen, JTextField pText) {
		super();
		iMaxLength = pMaxLen;
		txt = pText;
	}
	
	public void insertString(int pOffSet, String pString, AttributeSet pAttributSet)
	throws BadLocationException {
		if (pString == null)
			return;
		
		if (iMaxLength <= 0) {// aceitara qualquer no. de caracteres
			super.insertString(pOffSet, pString, pAttributSet);
			return;
		}
		
		long ilen = (getLength() + pString.length());
		try {
			 
			if(pString.length()==1 && !pString.equals("-"))
				setNum(Long.parseLong(pString));
			
			if(pString.equals("0") && txt.getText().length() == 0){
				/**return;*/
			}
			
			if (ilen <= iMaxLength) // se o comprimento final for menor...
				super.insertString(pOffSet, pString, pAttributSet); // ...aceita str
			else if (getLength() == iMaxLength)
				return; // nada a fazer
			else {	
				String newStr = pString.substring(0, (iMaxLength - getLength()));
				super.insertString(pOffSet, newStr, pAttributSet);
			}
		}
		catch(Exception e) {}
	}

	public long getNum() {
		return num;
	}

	public void setNum(long num) {
		this.num = num;
	}
}