/*******************************************************************************
***  This file is part of Dux Rei Nummariae.                                 ***
***                                                                          ***
***  Copyright (C) 2017, 2018, 2019, 2020, 2021                              ***
***  John Schneiderman <Licensing _AT_ Schneiderman _DOT_ me>                ***
***                                                                          ***
***  This program is free software: you can redistribute it and/or modify it ***
***  under the terms of the GNU Affero 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 Affero General Public License for more details.             ***
***                                                                          ***
***  You should have received a copy of the GNU Affero General Public License***
***  along with this program. If not, see <http://www.gnu.org/licenses/>.    ***
*******************************************************************************/
#include "DebtsWidget.h"
using pecunia::currency::Iso4217Codes;
using ::QString;
using ::QWidget;
using std::chrono::hours;
using std::function;
using std::set;
using drn::banking::BankAccount;
using drn::banking::BankName;
using drn::desktop_ui::internal::DebtsWidget;
using drn::foundation::Days;
using drn::foundation::ObserverPtr;
using drn::foundation::Optional;

#include <pecunia/Math.h>
using pecunia::math::sum;
#include <pecunia/Money.h>
using pecunia::currency::Money;
#include <QAbstractButton>
using ::QAbstractButton;
#include <QDebug>
// using qDebug.
#include <QPushButton>
using ::QPushButton;

#include <stdexcept>
using std::exception;
using std::logic_error;
#include <vector>
using std::vector;

#include <banking/BankAccount.h>
using drn::banking::BankAccount;
#include <budgeting/Algorithm.h>
using drn::budgeting::adjustTo;
#include <budgeting/BudgetSource.h>
using drn::budgeting::BudgetSource;
#include <budgeting/EventFrequency.h>
using drn::budgeting::EventFrequency;
#include <budgeting/Debt.h>
using drn::budgeting::Debt;
#include <budgeting/DebtMap.h>
using drn::budgeting::DebtMap;
#include <foundation/Error.h>
using drn::foundation::Error;
#include <foundation/QtMemory.hpp>
using drn::foundation::makeQtPtr;
#include "internal/DebtEntryWidget.h"
using drn::desktop_ui::internal::DebtEntryWidget;
#include <navigation/BudgetBankAccount.h>
using drn::navigation::BudgetBankAccount;
using drn::navigation::lookUpAccount;


Optional<ObserverPtr<DebtEntryWidget>> DebtsWidget::findDebt(
	const function<bool(const DebtEntryWidget&)>& isMatch
)
{
	for (const auto& debtEntry : this->findChildren<DebtEntryWidget*>())
		try
		{
			if (isMatch(*debtEntry))
				return {debtEntry};
		}
		catch (const exception& error)
		{
			qDebug() << "An error occurred while checking a debt entry." << error.what();
			continue;
		}
	return {};
}

void DebtsWidget::addDebt(const Optional<Debt>& d, const Optional<BankAccount>& ba)
{
	qDebug() << "Adding debt entry:" << d.valueOrDefault().source().name();
	auto ew{
		makeQtPtr<DebtEntryWidget>(
			d,
			ba,
			this->banks_,
			this->usableCurrencies_,
			this
		)
	};
	connect(
		ew.observed(),
		&DebtEntryWidget::valueChanged,
		this,
		&DebtsWidget::updateTotal
	);

	if ( ! d.hasValue())
		this->debtVbxlyt->insertWidget(0, ew.observed());
	else
		this->debtVbxlyt->insertWidget(
			this->debtVbxlyt->indexOf(this->debtBottomSpcr),
			ew.observed()
		);
}

bool DebtsWidget::anyDebtDirty() const
{
	for (const auto& debtEntry : this->findChildren<DebtEntryWidget*>())
		if (debtEntry->isDirty())
			return true;
	return false;
}

void DebtsWidget::addEntry()
{
	qDebug() << "Adding empty debt.";
	this->addDebt({}, {});
}

void DebtsWidget::saveDebts()
{
	qInfo() << "Saving all debts.";

	for (auto& debtEntry : this->findChildren<DebtEntryWidget*>())
	{
		qInfo() << "Examining Debt,"
			<< "Original Source:" << debtEntry->originalSource().valueOrDefault().name();

		try
		{
			if ( ! debtEntry->isDirty())
			{
				qInfo() << debtEntry->source().name() << "Debt Did Not Change.";
				continue;
			}
			else if (debtEntry->shouldRemove())
			{
				qInfo() << "Debt to be Removed";

				if (debtEntry->originalSource().hasValue())
					emit removed(*debtEntry->originalSource());
				// Resetting the dirty flag should the entry be examined before it's deleted.
				debtEntry->resetDirty();
				debtEntry->deleteLater();
				continue;
			}
			else if ( ! debtEntry->originalSource().hasValue())
			{
				qInfo() << "Debt to be Added:" << debtEntry->source().name();
				const Debt debt{
					debtEntry->source(),
					debtEntry->minimum(),
					debtEntry->period(),
					debtEntry->nextOccurOn(),
					debtEntry->borrowed(),
					debtEntry->interest()
				};
				const auto ba{
					[&debtEntry] () -> Optional<BankAccount>
					{
						const auto b{debtEntry->bank()};
						const auto sat{debtEntry->bankAccountType()};

						if (b.hasValue() && sat.hasValue())
							return BankAccount{*b, {{}, *sat}};
						return {};
					}()
				};
				emit added(debt, ba);
			}
			else // Must be an update or rename.
			{
				qInfo() << "Debt to be Updated:" << debtEntry->source().name();

				if (debtEntry->originalSource() != debtEntry->source())
					emit renamed(*debtEntry->originalSource(), debtEntry->source());
				const Debt debt{
					debtEntry->source(),
					debtEntry->minimum(),
					debtEntry->period(),
					debtEntry->nextOccurOn(),
					debtEntry->borrowed(),
					debtEntry->interest()
				};
				const auto ba{
					[&debtEntry] () -> Optional<BankAccount>
					{
						const auto b{debtEntry->bank()};
						const auto sat{debtEntry->bankAccountType()};

						if (b.hasValue() && sat.hasValue())
							return BankAccount{*b, {{}, *sat}};
						return {};
					}()
				};
				emit updated(debt, ba);
			}
		}
		catch (const Error& e)
		{
			qWarning() << "Error during the save data transformation." << e.what();
			debtEntry->setErrorMessage(e.message());
		}
	}
	qInfo() << "Processed all debts.";

	// Checking here in the event the user clicks save, and nothing was modified.
	if ( ! this->anyDebtDirty())
		this->close();
}

void DebtsWidget::updateTotal()
{
	qDebug() << "Updating debts total";
	vector<Money> items{};

	for (const auto& debt : this->findChildren<const DebtEntryWidget*>())
	{
		const Money amount{debt->minimum()};
		const EventFrequency period{debt->period()};

		if (
			period == EventFrequency::Unknown
			|| amount.code() == Iso4217Codes::XXX
			|| debt->shouldRemove()
		)
			continue;
		items.emplace_back(
			adjustTo(
				EventFrequency::Monthly,
				amount,
				period,
				this->hrInWeek_,
				this->dayInWeek_
			)
		);
	}
	const auto total{sum(this->preferred_, items)};
	this->totalMnyntr->setMoney(total);
}

void DebtsWidget::onClicked(const ObserverPtr<QAbstractButton>& button)
{
	qDebug() << "Handling debts button clicked" << button->text();

	if (this->saveDiscardBttnbx->button(QDialogButtonBox::Discard) == button)
		this->close();
	else if (this->saveDiscardBttnbx->button(QDialogButtonBox::Save) == button)
		this->saveDebts();
	else if (this->addPshbttn_.observed() == button)
		this->addEntry();
	else
		throw logic_error{"Unknown button pressed, " + button->text().toStdString() + '.'};
}

bool DebtsWidget::close()
{
	qDebug() << "The debts widget is about to close.";
	emit closing();
	return QWidget::close();
}

void DebtsWidget::onSaveSucceeded(const BudgetSource& source)
{
	qInfo() << "Succeeded to save" << source.name();
	auto debt{
		this->findDebt(
			[&source] (const auto& entry)
			{
				return entry.originalSource() == source
					|| ( ! entry.originalSource().hasValue() && entry.source() == source);
			}
		)
	};

	if ( ! debt.hasValue())
	{
		qFatal("Failed to locate the debt that succeeded to be saved.");
		return;
	}
	(*debt)->saved();
	qDebug() << "Checking if everything is saved.";

	if ( ! this->anyDebtDirty())
		this->close();
}

void DebtsWidget::onSaveFailed(
	const Optional<BudgetSource>& original,
	const QString& errorMessage,
	const Optional<BudgetSource>& displayed
)
{
	qWarning() << "Failed to save,"
			<< "Original Source"<< original.valueOrDefault().name()
			<< "Displayed Source" << displayed.valueOrDefault().name()
			<< errorMessage;
	auto debt{
		this->findDebt(
			[&original, &displayed] (const auto& entry)
			{
				const auto sameOriginal{entry.originalSource() == original};
				const auto sameDisplayed{entry.source() == displayed};
				return sameOriginal && sameDisplayed;
			}
		)
	};

	if ( ! debt.hasValue())
	{
		qFatal("Failed to locate the debt that failed to be saved.");
		return;
	}
	(*debt)->setErrorMessage(errorMessage);
}

DebtsWidget::DebtsWidget(
	const DebtMap& debts,
	const set<BudgetBankAccount>& accounts,
	const hours& hrInWeek,
	const Days& dayInWeek,
	set<BankName> banks,
	const Iso4217Codes& preferred,
	const set<Iso4217Codes>& usableCurrencies,
	const ObserverPtr<QWidget> parent
) :
	QWidget{parent.observed()},
	hrInWeek_{hrInWeek},
	dayInWeek_{dayInWeek},
	banks_{std::move(banks)},
	preferred_{preferred},
	usableCurrencies_{usableCurrencies},
	addPshbttn_{nullptr}
{
	this->setAttribute(Qt::WA_DeleteOnClose);
	this->setupUi(this);
	this->totalMnyntr->setUsableCodes(this->usableCurrencies_);
	this->totalMnyntr->setLabel(tr("Monthly Total Amount:"));

	if (debts.empty())
		this->addEntry();
	else
		for (const auto& debt : debts)
			this->addDebt(debt.second, lookUpAccount(debt.first, accounts));
	this->updateTotal();

	//{ Set-up Add Button

	connect(
		this->saveDiscardBttnbx,
		&QDialogButtonBox::clicked,
		this,
		&DebtsWidget::onClicked
	);
	this->addPshbttn_ = this->saveDiscardBttnbx->addButton(
		tr("&Add"),
		QDialogButtonBox::ButtonRole::ActionRole
	);

	if (this->addPshbttn_ == nullptr)
		throw Error{QObject::tr("Failed to create the add push button.")};

	//}
}
