package info.bukova.isspst.ui;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.bind.BindContext;
import org.zkoss.bind.Converter;
import org.zkoss.util.Locales;
import org.zkoss.zk.ui.Component;

public class BigDecimalConverter implements Converter<String, BigDecimal, Component>
{
	private final static Logger log = LoggerFactory.getLogger(BigDecimalConverter.class.getName());

	@Override
	public BigDecimal coerceToBean(String str, Component component, BindContext cx)
	{
		BigDecimal val = BigDecimal.ZERO;
		
		if (str != null)
		{
			try
			{
				Locale loc = Locales.getCurrent();
				DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(loc);
				format.setParseBigDecimal(true);
				val = (BigDecimal) format.parse(str);
			}
			catch (NumberFormatException e)
			{
				log.warn(str, e);
			}
			catch (ParseException e)
			{
				log.warn(str, e);
			}
		}
		
		return val;
	}

	@Override
	public String coerceToUi(BigDecimal val, Component component, BindContext cx)
	{
		// String lang = Executions.getCurrent().getHeader("accept-language");
		Locale loc = Locales.getCurrent();

		if (val == null)
		{
			val = BigDecimal.ZERO;
		}

		val = val.setScale(2, BigDecimal.ROUND_DOWN);

		DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(loc);
		format.setMaximumFractionDigits(2);
		format.setMinimumFractionDigits(2);
		format.setGroupingUsed(true);
		format.setGroupingSize(3);
		String formatted = format.format(val);
		return formatted;
	}

}
