/*
 * Copyright (C) 2023 ctecinf.com.br
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package br.com.ctecinf.text;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import javax.swing.JFormattedTextField;

/**
 *
 * @author Cássio Conceição
 * @since 01/11/2019
 * @version 2305
 * @see http://ctecinf.com.br/
 */
public class NumberFormatter extends JFormattedTextField.AbstractFormatter {

    private NumberFormat nf;

    /**
     * Construtor para número fracionário
     *
     * @param fractionDigits
     */
    public NumberFormatter(int fractionDigits) {
        setNumberFormat(fractionDigits);
    }

    private void setNumberFormat(int fractionDigits) {

        nf = DecimalFormat.getNumberInstance(new Locale("pt", "BR"));
        nf.setMinimumFractionDigits(fractionDigits);
        nf.setMaximumFractionDigits(fractionDigits);

        if (fractionDigits == 0) {
            nf.setGroupingUsed(false);
            nf.setParseIntegerOnly(true);
        }
    }

    @Override
    public Number stringToValue(String text) throws ParseException {

        return text == null || text.isEmpty() ? new Number() {

            @Override
            public int intValue() {
                return 0;
            }

            @Override
            public long longValue() {
                return 0l;
            }

            @Override
            public float floatValue() {
                return 0f;
            }

            @Override
            public double doubleValue() {
                return 0.00;
            }
        } : nf.parse(text);
    }

    @Override
    public String valueToString(final Object value) throws ParseException {

        if (value == null) {
            return "";
        }

        Number num;

        if (value instanceof Number) {
            num = (Number) value;
        } else {

            num = new Number() {

                @Override
                public int intValue() {
                    return Integer.parseInt(value.toString());
                }

                @Override
                public long longValue() {
                    return Long.parseLong(value.toString());
                }

                @Override
                public float floatValue() {
                    return Float.parseFloat(value.toString());
                }

                @Override
                public double doubleValue() {
                    return Double.parseDouble(value.toString());
                }
            };
        }

        return nf.format(num);
    }

    public static NumberFormat format() {
        return format(2);
    }

    public static NumberFormat format(int fractionDigits) {
        return format(fractionDigits, new Locale("pt", "BR"), fractionDigits == 0);
    }

    public static NumberFormat format(int fractionDigits, Locale locale, boolean grouping) {

        NumberFormat numberFormat = DecimalFormat.getNumberInstance(locale);
        numberFormat.setMinimumFractionDigits(fractionDigits);
        numberFormat.setMaximumFractionDigits(fractionDigits);

        numberFormat.setGroupingUsed(grouping);

        if (fractionDigits == 0) {
            numberFormat.setParseIntegerOnly(true);
        }

        return numberFormat;
    }

    /**
     * Formato americano com 2 dígitos
     *
     * @param value
     * @return String
     */
    public static String formatUS2Digits(Object value) {
        return formatUS(value, 2);
    }

    /**
     * Formato americano com 4 dígitos
     *
     * @param value
     * @return String
     */
    public static String formatUS4Digits(Object value) {
        return formatUS(value, 4);
    }

    /**
     * Formato americano
     *
     * @param value
     * @param fractionDigits Número de dígitos
     * @return String
     */
    public static String formatUS(Object value, int fractionDigits) {
        NumberFormat nf = NumberFormatter.get(fractionDigits, Locale.US);
        return nf.format(value);
    }

    /**
     * Transforma String formato americano para double
     *
     * @param value
     * @return double
     * @throws java.text.ParseException
     */
    public static double parseUS2Digits(String value) throws ParseException {
        return NumberFormatter.get(2, Locale.US).parse(value == null ? "0" : value).doubleValue();
    }

    /**
     *
     * @param fractionDigits
     * @param locale
     * @return NumberFormat
     */
    private static NumberFormat get(int fractionDigits, Locale locale) {

        NumberFormat nf = DecimalFormat.getNumberInstance(locale);
        nf.setMinimumFractionDigits(fractionDigits);
        nf.setMaximumFractionDigits(fractionDigits);

        if (fractionDigits == 0) {
            nf.setGroupingUsed(false);
            nf.setParseIntegerOnly(true);
        }

        return nf;
    }
}
