/*******************************************************************************
***  This file is part of Pecunia.                                           ***
***                                                                          ***
***  Copyright (C) 2017, 2018, 2019, 2020, 2021, 2023                        ***
***  John Schneiderman <Licencing _AT_ Schneiderman _DOT_ me>                ***
***                                                                          ***
***  This program is free software: you can redistribute it and/or modify it ***
***  under the terms of the GNU Lesser 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 Lesser General Public License for more details.             ***
***                                                                          ***
***  You should have received a copy of the GNU Lesser General Public License***
***  along with this program. If not, see <http://www.gnu.org/licenses/>.    ***
*******************************************************************************/
#include "Math.h"
using std::function;
using std::map;
using pecunia::currency::Iso4217Codes;
using pecunia::currency::Money;

#include <cmath>
using std::abs;
#include <numeric>
using std::accumulate;


Money pecunia::math::absoluteValue(const Money& money) // cppcheck-suppress unusedFunction
{
	auto copy{money};
	copy.amount_ = abs(copy.amount_);
	return copy;
}

void pecunia::math::internal::addToRunningTotals(
	map<Iso4217Codes, Money>& runningTotals,
	const Money& amount,
	const function<Money(const Money &)>& adjustor
)
{
	if (runningTotals.count(amount.code()) == 0)
		runningTotals[amount.code()].setCode(amount.code());
	runningTotals[amount.code()] += adjustor == nullptr ? amount : adjustor(amount);
}

Money pecunia::math::internal::accumulateRunningTotals(
	const Iso4217Codes& accumulateCurrency,
	const map<Iso4217Codes, Money>& totals
)
{
	const auto total{
		accumulate(
			totals.cbegin(),
			totals.cend(),
			Money{accumulateCurrency},
			[] (const auto& accumulator, const auto& currencyRunningTotals)
			{
				return accumulator + currencyRunningTotals.second;
			}
		)
	};
	return total;
}
