/**
 * Licensed under the MICE s.r.l.
 * End User License Agreement
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.micegroup.it/voila/license.html
 */
package it.mice.voila.runtime.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;

/**
 * Utility class for JMS names.
 * <p/>
 * Contains the following methods:
 * <ul>
 * <li> getQueueConnectionFactory
 * <li> getQueue
 * <li> jndiLookup
 * </ul>
 */
public class FormatterUtil {
    private static ThreadLocal currentLocale = new ThreadLocal() {
        protected synchronized Object initialValue() {
            return null;
        }
    };

    public static Locale getCurrentLocale() {
        return (Locale) currentLocale.get();
    }

    public static void setCurrentLocale(Locale currentLocale) {
        FormatterUtil.currentLocale.set(currentLocale);
    }

    /**
     * Ritorna il valore dell'attributo come stringa
     */
    public static String formatAttributeToString(Object attribute) throws RuntimeException {

        if (attribute == null)
            return null;

        String valueString = attribute.toString();

        if (attribute instanceof java.util.Date) {
            SimpleDateFormat dfOut = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALIAN);
            valueString = dfOut.format(attribute);
        }

        if (attribute instanceof java.lang.Number) {
            DecimalFormatSymbols dfs = new DecimalFormatSymbols();
            dfs.setDecimalSeparator(',');
            dfs.setGroupingSeparator('.');
            DecimalFormat formatter = new DecimalFormat("#.#################", dfs);
            valueString = formatter.format(attribute);
        }

        return valueString;
    }

    /**
     * Convert date string in a timestamp value.
     *
     * @return Timestamp of a date value in a string
     */
    public static Timestamp formatAttributeToTimestamp(String date) {
        if (date == null || date.length() == 0) {
            return null;
        }
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALIAN);
        try {
            return new java.sql.Timestamp(df.parse(date).getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Convert string into a BigDecimal in a null safe mode.
     *
     * @return BigDecimal format for the given string value
     */
    public static BigDecimal formatAttributeToBigDecimal(String value) {
        BigDecimal retValue;
        try {
            String realValue = formatToReal(value);
            retValue = (realValue == null) ? null : new BigDecimal(realValue);
        } catch (RuntimeException e) {
            retValue = null;
        }
        return retValue;
    }

    /**
     * Convert string into a BigInteger in a null safe mode.
     *
     * @return BigInteger format for the given string value
     */
    public static BigInteger formatAttributeToBigInteger(String value) {
        BigInteger retValue;
        try {
            String realValue = formatToReal(value);
            retValue = (realValue == null) ? null : new BigInteger(realValue);
        } catch (RuntimeException e) {
            retValue = null;
        }
        return retValue;
    }

    /**
     * Convert string into a Integer in a null safe mode.
     *
     * @return Integer format for the given string value
     */
    public static Integer formatAttributeToInteger(String value) {
        Integer retValue;
        try {
            String realValue = formatToReal(value);
            retValue = (realValue == null) ? null : new Integer(realValue);
        } catch (RuntimeException e) {
            retValue = null;
        }
        return retValue;
    }

    /**
     * Convert string into a Byte in a null safe mode.
     *
     * @return Byte format for the given string value
     */
    public static Byte formatAttributeToByte(String value) {
        Byte retValue;
        try {
            String realValue = formatToReal(value);
            retValue = (realValue == null) ? null : new Byte(realValue);
        } catch (RuntimeException e) {
            retValue = null;
        }
        return retValue;
    }

    /**
     * Convert string into a Float in a null safe mode.
     *
     * @return Float format for the given string value
     */
    public static Float formatAttributeToFloat(String value) {
        Float retValue;
        try {
            String realValue = formatToReal(value);
            retValue = (realValue == null) ? null : new Float(realValue);
        } catch (RuntimeException e) {
            retValue = null;
        }
        return retValue;
    }

    /**
     * Convert string into a Double in a null safe mode.
     *
     * @return Double format for the given string value
     */
    public static Double formatAttributeToDouble(String value) {
        Double retValue;
        try {
            String realValue = formatToReal(value);
            retValue = (realValue == null) ? null : new Double(realValue);
        } catch (RuntimeException e) {
            retValue = null;
        }
        return retValue;
    }

    /**
     * Convert string into a Short in a null safe mode.
     *
     * @return Short format for the given string value
     */
    public static Short formatAttributeToShort(String value) {
        Short retValue;
        try {
            String realValue = formatToReal(value);
            retValue = (realValue == null) ? null : new Short(realValue);
        } catch (RuntimeException e) {
            retValue = null;
        }
        return retValue;
    }

    /**
     * Convert string into a Long in a null safe mode.
     *
     * @return Long format for the given string value
     */
    public static Long formatAttributeToLong(String value) {
        Long retValue;
        try {
            String realValue = formatToReal(value);
            retValue = (realValue == null) ? null : new Long(realValue);
        } catch (RuntimeException e) {
            retValue = null;
        }
        return retValue;
    }

    /**
     * Ritorna il valore dell'attributo come stringa
     */
    public static String formatAttribute(String javaType, String valueAttribute) throws Exception {

        String valueString = valueAttribute;

        if (valueAttribute == null)
            return null;

        if (javaType.equals("java.sql.Date")) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ITALIAN);
            java.util.Date valueDate = df.parse(valueAttribute);
            SimpleDateFormat dfOut = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALIAN);
            valueString = dfOut.format(valueDate);
        }

        return valueString;
    }

    /**
     * Ritorna il valore dell'attributo immesso dall'utente nel formato reale (riconosciuto dal DB)
     */
    public static String formatToReal(String valueAttribute) throws RuntimeException {
        if (valueAttribute == null || valueAttribute.trim().length() == 0)
            return null;

        String groupSymbol = getGroupSeparator();
        String decimalSymbol = getDecimalSeparator();

        valueAttribute = StringUtils.replace(valueAttribute, groupSymbol, "");
        valueAttribute = StringUtils.replace(valueAttribute, decimalSymbol, ".");

        return valueAttribute;
    }

    private static String getDecimalSeparator() {
        return ",";
    }

    private static String getGroupSeparator() {
        return ".";
    }
    
    public Object defaultIfNull(Object value, Object defaultIfNull) {
    	return (value != null ? value : defaultIfNull);
    }
    
    public Object defaultIfEmpty(Object value, Object defaultIfNull) {
    	return (value == null || StringUtils.isEmpty(value + "") ? defaultIfNull : value);
    }
}
