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


Optional<ObserverPtr<NontrackEntryWidget>> NontracksWidget::findNontrack(
	const function<bool(const NontrackEntryWidget&)>& isMatch
)
{
	for (const auto& nontrackEntry : this->findChildren<NontrackEntryWidget*>())
		try
		{
			if (isMatch(*nontrackEntry))
				return {nontrackEntry};
		}
		catch (const exception& error)
		{
			qDebug() << "An error occurred while checking a nontrack entry." << error.what();
			continue;
		}
	return {};
}

void NontracksWidget::addNontrack(const Nontrack& nontrack, const bool isNew)
{
	qDebug() << "Adding nontrack entry:" << nontrack.source().name() << "isNew" << isNew;
	auto ew{makeQtPtr<NontrackEntryWidget>(nontrack, this->usableCurrencies_, this)};
	connect(
		ew.observed(),
		&NontrackEntryWidget::valueChanged,
		this,
		&NontracksWidget::updateTotal
	);

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

bool NontracksWidget::anyNontrackDirty() const
{
	for (const auto& nontrackEntry : this->findChildren<NontrackEntryWidget*>())
		if (nontrackEntry->isDirty())
			return true;
	return false;
}

void NontracksWidget::addEntry()
{
	qDebug() << "Adding empty nontrack.";
	this->addNontrack(Nontrack{}, true);
}

void NontracksWidget::saveNontracks()
{
	qInfo() << "Saving all nontracks.";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

NontracksWidget::NontracksWidget(
	const NontrackMap& nontracks,
	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 (nontracks.empty())
		this->addEntry();
	else
		for (const auto& nontrack : nontracks)
			this->addNontrack(nontrack.second, false);
	this->updateTotal();

	//{ Set-up Add Button

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

	//}
}
