/* UtilLib - Copyright (c) 2016-2018 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.money;

import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import net.mapeadores.util.primitives.Decimal;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
public final class Amount {

    private final long moneyLong;
    private final ExtendedCurrency currency;

    public Amount(long moneyLong, ExtendedCurrency currency) {
        this.moneyLong = moneyLong;
        this.currency = currency;
    }

    public long getMoneyLong() {
        return moneyLong;
    }

    public ExtendedCurrency getCurrency() {
        return currency;
    }

    public String getCurrencyCode() {
        return currency.getCurrencyCode();
    }

    public Decimal toDecimal(boolean avoidDecimal) {
        return MoneyLong.toDecimal(moneyLong, currency.getDefaultFractionDigits(), avoidDecimal);
    }

    @Override
    public String toString() {
        return MoneyLong.toString(moneyLong, currency.getDefaultFractionDigits());
    }

    public String toLitteralString(DecimalFormatSymbols symbols, boolean avoidDecimal) {
        return MoneyUtils.toLitteralString(moneyLong, currency, symbols, avoidDecimal);
    }

    public static Amount parse(String s) throws ParseException {
        String[] result = MoneyUtils.splitMoney(s);
        if (result == null) {
            throw new ParseException(s, 0);
        }
        Decimal decimal;
        try {
            decimal = StringUtils.parseDecimal(result[0]);
        } catch (NumberFormatException nfe) {
            throw new ParseException(result[0], 0);
        }
        ExtendedCurrency currency;
        try {
            currency = ExtendedCurrency.parse(result[1]);
        } catch (ParseException pe) {
            throw new ParseException(result[1], 0);
        }
        return new Amount(MoneyLong.toMoneyLong(decimal, currency.getDefaultFractionDigits()), currency);
    }

}
