/* FichothequeLib_Tools - Copyright (c) 2015-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.fichotheque.tools.exportation.table.columnsum;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import net.mapeadores.util.money.Amount;
import net.mapeadores.util.money.ExtendedCurrency;
import net.fichotheque.exportation.table.SumResult;


/**
 *
 * @author Vincent Calame
 */
public class MoneyColumnSumBuilder extends ColumnSumBuilder {

    private final SortedMap<ExtendedCurrency, ValueSum> currencyMap = new TreeMap<ExtendedCurrency, ValueSum>();

    public MoneyColumnSumBuilder() {

    }

    public void sum(Amount amount) {
        ExtendedCurrency currency = amount.getCurrency();
        ValueSum valueSum = currencyMap.get(currency);
        if (valueSum == null) {
            valueSum = new ValueSum();
            currencyMap.put(currency, valueSum);
        }
        valueSum.add(amount.getMoneyLong());
    }

    @Override
    public SumResult.ColumnSum toColumnSum() {
        int size = currencyMap.size();
        if (size == 0) {
            return null;
        }
        Amount[] resultArray = new Amount[size];
        int p = 0;
        for (Map.Entry<ExtendedCurrency, ValueSum> entry : currencyMap.entrySet()) {
            resultArray[p] = new Amount(entry.getValue().result, entry.getKey());
            p++;
        }
        return new InternalMoneyColumnSum(resultArray);
    }


    private static class ValueSum {

        private long result = 0;

        private ValueSum() {

        }

        private void add(long l) {
            result = result + l;
        }

    }


    private static class InternalMoneyColumnSum implements SumResult.MoneyColumnSum {

        private final Amount[] resultArray;

        private InternalMoneyColumnSum(Amount[] resultArray) {
            this.resultArray = resultArray;
        }

        @Override
        public int getResultCount() {
            return resultArray.length;
        }

        @Override
        public Amount getResult(int i) {
            return resultArray[i];
        }

    }


}
