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


Optional<ObserverPtr<WageEntryWidget>> WagesWidget::findWage(
	const function<bool(const WageEntryWidget&)>& isMatch
)
{
	for (const auto& wageEntry : this->findChildren<WageEntryWidget*>())
		try
		{
			if (isMatch(*wageEntry))
				return {wageEntry};
		}
		catch (const exception& error)
		{
			qDebug() << "An error occurred while checking a wage entry." << error.what();
			continue;
		}
	return {};
}

void WagesWidget::addWage(const Wage& wage, const bool isNew)
{
	qDebug() << "Adding wage entry:" << wage.source().name() << "isNew" << isNew;
	auto ew{makeQtPtr<WageEntryWidget>(wage, this->usableCurrencies_, this)};
	connect(
		ew.observed(),
		&WageEntryWidget::valueChanged,
		this,
		&WagesWidget::updateTotal
	);

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

bool WagesWidget::anyWageDirty() const
{
	for (const auto& wageEntry : this->findChildren<WageEntryWidget*>())
		if (wageEntry->isDirty())
			return true;
	return false;
}

void WagesWidget::addEntry()
{
	qDebug() << "Adding empty wage.";
	this->addWage(Wage{}, true);
}

void WagesWidget::saveWages()
{
	qInfo() << "Saving all wages.";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

WagesWidget::WagesWidget(
	const WageMap& wages,
	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 (wages.empty())
		this->addEntry();
	else
		for (const auto& wage : wages)
			this->addWage(wage.second, false);
	this->updateTotal();

	//{ Set-up Add Button

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

	//}
}
