/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rjconsultores.ventaboletos.web.utilerias;

import java.math.BigDecimal;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zul.Constraint;

/**
 * 
 * @author Gleimar
 */
public class ConstraintNumberBD implements Constraint {

	private Integer precision;
	private Integer scale;
	private Boolean obligatorio = false;

	/**
	 * Ex.: (precision,scale) == (3,2) Va a aceptar numero menores que 9.99
	 * 
	 * @param preicion
	 *            - La precision del numero
	 * @param scale
	 *            - La escala
	 */
	public ConstraintNumberBD(Integer preicion, Integer scale) {
		this(preicion, scale, false);
	}

	public ConstraintNumberBD(Integer preicion, Integer scale, Boolean obligatorio) {
		if ((preicion == null) || (scale == null)) {
			throw new IllegalArgumentException("Deve ser informado o valor de precisao e escala.");
		}
		this.precision = preicion;
		this.scale = scale;
		this.obligatorio = obligatorio;
	}

	public void validate(Component comp, Object value) throws WrongValueException {

		if ((precision != null) && (scale != null)) {

			if ((value != null) && (value instanceof String)) {
				value = (((String) value).trim().equals("")) ? null : value;
			}
			if (obligatorio && (value == null)) {
				throw new WrongValueException(comp,
						Labels.getLabel("MSG.CONSTRAINT.CONSTRAINTNUMBERBDOBLIGATORIO"));
			}

			if (value == null) {
				return;
			}

			try {
				BigDecimal valor = getBigDecimal(value);

				if ((valor.precision() > precision) || (valor.scale() > scale)) {
					throw new WrongValueException(comp,
							Labels.getLabel("MSG.CONSTRAINT.CONSTRAINTNUMBERBD", new Object[] { precision - 2, scale }));
				}
			} catch (NumberFormatException n) {
				throw new WrongValueException(comp,Labels.getLabel("MSG.CONSTRAINT.CONSTRAINTNUMBERBD.EXCEPTION"));
			}
		}
	}

	private BigDecimal getBigDecimal(Object value) throws NumberFormatException {

		if (value instanceof BigDecimal) {
			return (BigDecimal) value;
		}

		return new BigDecimal(((String) value).replace(",", ""));
	}
}
