/*******************************************************************************
***  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 "BillsWidget.h"
using pecunia::currency::Iso4217Codes;
using ::QString;
using ::QWidget;
using std::chrono::hours;
using std::function;
using std::set;
using drn::desktop_ui::internal::BillsWidget;
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 <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/Bill.h>
using drn::budgeting::Bill;
#include <budgeting/BillMap.hpp>
using drn::budgeting::BillMap;
#include <foundation/Error.h>
using drn::foundation::Error;
#include <foundation/QtMemory.hpp>
using drn::foundation::makeQtPtr;
#include "internal/BillEntryWidget.h"
using drn::desktop_ui::internal::BillEntryWidget;


Optional<ObserverPtr<BillEntryWidget>> BillsWidget::findBill(
	const function<bool(const BillEntryWidget&)>& isMatch
)
{
	for (const auto& billEntry : this->findChildren<BillEntryWidget*>())
		try
		{
			if (isMatch(*billEntry))
				return {billEntry};
		}
		catch (const exception& error)
		{
			qDebug() << "An error occurred while checking a bill entry." << error.what();
			continue;
		}
	return {};
}

void BillsWidget::addBill(const Bill& bill, const bool isNew)
{
	qDebug() << "Adding bill entry:" << bill.source().name() << "isNew" << isNew;
	auto ew{makeQtPtr<BillEntryWidget>(bill, this->usableCurrencies_, this)};
	connect(
		ew.observed(),
		&BillEntryWidget::valueChanged,
		this,
		&BillsWidget::updateTotal
	);

	if (isNew)
		this->billVbxlyt->insertWidget(0, ew.observed());
	else
		this->billVbxlyt->insertWidget(
			this->billVbxlyt->indexOf(this->billBottomSpcr),
			ew.observed()
		);
}

bool BillsWidget::anyBillDirty() const
{
	for (const auto& billEntry : this->findChildren<BillEntryWidget*>())
		if (billEntry->isDirty())
			return true;
	return false;
}

void BillsWidget::addEntry()
{
	qDebug() << "Adding empty bill.";
	this->addBill(Bill{}, true);
}

void BillsWidget::saveBills()
{
	qInfo() << "Saving all bills.";

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

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

				if (billEntry->originalSource().hasValue())
					emit removed(*billEntry->originalSource());
				// Resetting the dirty flag should the entry be examined before it's deleted.
				billEntry->resetDirty();
				billEntry->deleteLater();
				continue;
			}
			else if ( ! billEntry->originalSource().hasValue())
			{
				qInfo() << "Bill to be Added:" << billEntry->source().name();
				const Bill bill{
					billEntry->source(),
					billEntry->amount(),
					billEntry->period(),
					billEntry->nextOccurOn()
				};
				emit added(bill);
			}
			else // Must be an update or rename.
			{
				qInfo() << "Bill to be Updated:" << billEntry->source().name();

				if (billEntry->originalSource() != billEntry->source())
					emit renamed(*billEntry->originalSource(), billEntry->source());
				const Bill bill{
					billEntry->source(),
					billEntry->amount(),
					billEntry->period(),
					billEntry->nextOccurOn()
				};
				emit updated(bill);
			}
		}
		catch (const Error& e)
		{
			qWarning() << "Error during the save data transformation." << e.what();
			billEntry->setErrorMessage(e.message());
		}
	}
	qInfo() << "Processed all bills.";

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

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

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

		if (
			period == EventFrequency::Unknown
			|| amount.code() == Iso4217Codes::XXX
			|| bill->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 BillsWidget::onClicked(ObserverPtr<QAbstractButton> button)
{
	qDebug() << "Handling bills button clicked" << button->text();

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

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

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

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

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

void BillsWidget::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 bill{
		this->findBill(
			[&original, &displayed] (const auto& entry)
			{
				const auto sameOriginal{entry.originalSource() == original};
				const auto sameDisplayed{entry.source() == displayed};
				return sameOriginal && sameDisplayed;
			}
		)
	};

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

BillsWidget::BillsWidget(
	const BillMap& bills,
	const hours& hrInWeek,
	const Days& dayInWeek,
	const Iso4217Codes& preferred,
	const set<Iso4217Codes>& usableCurrencies,
	const ObserverPtr<QWidget>& parent
) :
	QWidget{parent.observed()},
	hrInWeek_{hrInWeek},
	dayInWeek_{dayInWeek},
	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 (bills.empty())
		this->addEntry();
	else
		for (const auto& bill : bills)
			this->addBill(bill.second, false);
	this->updateTotal();

	//{ Set-up Add Button

	connect(
		this->saveDiscardBttnbx,
		&QDialogButtonBox::clicked,
		this,
		&BillsWidget::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.")};

	//}
}
