/*******************************************************************************
***  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 "DebtEntryWidget.h"
using ::QWidget;
using std::set;
using drn::budgeting::BudgetSource;
using drn::desktop_ui::internal::DebtEntryWidget;
using drn::foundation::Optional;
using drn::foundation::SwitchStates;

#include <pecunia/Codes.h>
using pecunia::currency::Iso4217Codes;
#include <pecunia/Money.h>
using pecunia::currency::Money;
#include <QDate>
using ::QDate;
#include <QDebug>
// using qDebug
#include <QString>
using ::QString;

#include <exception>
using std::exception;

#include <accounting/Account.h>
using drn::accounting::AccountTypes;
#include <banking/BankAccount.h>
using drn::banking::BankAccount;
#include <banking/BankName.h>
using drn::banking::BankName;
#include <banking/BankAccountType.h>
using drn::banking::allSupportedAccountTypes;
using drn::banking::SupportedAccountTypes;
using drn::banking::toAccountTypes;
#include <budgeting/EventFrequency.h>
using drn::budgeting::EventFrequency;
#include <budgeting/Debt.h>
using drn::budgeting::Debt;
using drn::budgeting::Percentage;
#include <foundation/ObserverPtr.hpp>
using drn::foundation::ObserverPtr;


namespace
{

set<SupportedAccountTypes> debtAccountTypes()
{
	set<SupportedAccountTypes> sats{};

	for (const auto& bankAccountType : allSupportedAccountTypes)
		if (toAccountTypes(bankAccountType) == AccountTypes::Liability)
			sats.insert(bankAccountType);
	return sats;
}

}

void DebtEntryWidget::markDirty()
{
	qDebug() << "Debt Entry Widget is Dirty:" << this->sourceLndt->text();
	this->isDirty_.flipOn();
}

DebtEntryWidget::DebtEntryWidget(
	const Optional<Debt>& debt,
	const Optional<BankAccount>& ba,
	const set<BankName>& banks,
	const set<Iso4217Codes>& usableCurrencies,
	const ObserverPtr<QWidget> parent
) :
	QWidget{parent.observed()},
	isDirty_{SwitchStates::Off},
	original_{debt.hasValue() ? debt->source() : Optional<BudgetSource>{}}
{
	this->setupUi(this);
	this->borrowedAmountEntry->setUsableCodes(usableCurrencies);
	this->borrowedAmountEntry->setLabel(tr("Total Borrowed:"));
	this->minimumAmount->setLabel(tr("Minimum Payment:"));
	this->minimumAmount->setUsableCodes(usableCurrencies);

	if (debt.hasValue())
	{
		this->sourceLndt->setText(this->original_->name());
		this->sourceLndt->setCursorPosition(0);
		this->nextOccurOnDtdt->setDate(debt->nextOccurOn());
		// As this amount is tied to the initial balance of the account it cannot be directly
		// modified after creation.
		this->borrowedAmountEntry->setReadOnly(true);
		this->borrowedAmountEntry->setMoney(debt->borrowed());
		this->frequencyEntry->setFrequency(debt->period());
		this->minimumAmount->setMoney(debt->amount());
		this->interestDblspnbx->setValue(debt->interest().rate_);
	}
	else
	{
		this->nextOccurOnDtdt->setDate(QDate::currentDate());
		this->borrowedAmountEntry->setMoney({});
		this->frequencyEntry->setFrequency(EventFrequency::Unknown);
		this->minimumAmount->setMoney({});
		this->interestDblspnbx->setValue({});
	}
	this->minimumAmount->hideCodes();
	this->errorMessageLbl->hide();
	this->borrowedFromCmbbx->setBanks(banks);
	this->borrowedFromCmbbx->setSupportedAccountTypes(debtAccountTypes());

	if (ba.hasValue())
		this->borrowedFromCmbbx->setBankAccount(*ba);
	this->borrowedFromCmbbx->hideAccountCodes();

	//{ Update Error Message Colour

	QPalette error{this->errorMessageLbl->palette()};
	error.setColor(this->errorMessageLbl->foregroundRole(), Qt::red);
	this->errorMessageLbl->setPalette(error);

	//}

	connect(
		this->sourceLndt,
		&QLineEdit::textEdited,
		this,
		&DebtEntryWidget::markDirty
	);
	connect(
		this->borrowedAmountEntry,
		&MoneyEntryWidget::editingFinished,
		this,
		&DebtEntryWidget::markDirty
	);
	connect(
		this->borrowedAmountEntry,
		static_cast<void(MoneyEntryWidget::*)(int)>(&MoneyEntryWidget::currentIndexChanged),
		this,
		&DebtEntryWidget::markDirty
	);
	connect(
		this->frequencyEntry,
		static_cast<void(EventFrequencyEntryWidget::*)(int)>(
			&EventFrequencyEntryWidget::currentIndexChanged
		),
		this,
		&DebtEntryWidget::markDirty
	);
	connect(
		this->frequencyEntry,
		static_cast<void(EventFrequencyEntryWidget::*)(int)>(
			&EventFrequencyEntryWidget::currentIndexChanged
		),
		this,
		&DebtEntryWidget::valueChanged
	);
	connect(
		this->minimumAmount,
		&MoneyEntryWidget::editingFinished,
		this,
		&DebtEntryWidget::markDirty
	);
	connect(
		this->minimumAmount,
		&MoneyEntryWidget::editingFinished,
		this,
		&DebtEntryWidget::valueChanged
	);
	connect(
		this->borrowedAmountEntry,
		static_cast<void(MoneyEntryWidget::*)(int)>(&MoneyEntryWidget::currentIndexChanged),
		this->minimumAmount,
		static_cast<void(MoneyEntryWidget::*)(int)>(&MoneyEntryWidget::setCurrentIndex)
	);
	connect(
		this->minimumAmount,
		static_cast<void(MoneyEntryWidget::*)(int)>(&MoneyEntryWidget::currentIndexChanged),
		this,
		&DebtEntryWidget::valueChanged
	);
	connect(
		this->interestDblspnbx,
		static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
		this,
		&DebtEntryWidget::markDirty
	);
	connect(
		this->removeChckbx,
		&QCheckBox::stateChanged,
		this,
		&DebtEntryWidget::markDirty
	);
	connect(
		this->removeChckbx,
		&QCheckBox::stateChanged,
		this,
		&DebtEntryWidget::valueChanged
	);
	connect(
		this->nextOccurOnDtdt,
		&QDateEdit::dateChanged,
		this,
		&DebtEntryWidget::markDirty
	);
	connect(
		this->borrowedFromCmbbx,
		&BankAccountsWidget::changedBankName,
		this,
		&DebtEntryWidget::markDirty
	);
	connect(
		this->borrowedFromCmbbx,
		&BankAccountsWidget::changedBankAccountType,
		this,
		&DebtEntryWidget::markDirty
	);
}

const Optional<BudgetSource>& DebtEntryWidget::originalSource() const
{
	return this->original_;
}

BudgetSource DebtEntryWidget::source() const
{
	auto text{this->sourceLndt->text()};

	if (text.isEmpty())
		return {};
	return BudgetSource{std::move(text)};
}

Money DebtEntryWidget::borrowed() const
{
	return this->borrowedAmountEntry->money();
}

EventFrequency DebtEntryWidget::period() const
{
	return this->frequencyEntry->frequency();
}

Money DebtEntryWidget::minimum() const
{
	return this->minimumAmount->money();
}

Percentage DebtEntryWidget::interest() const
{
	return Percentage{this->interestDblspnbx->value()};
}

QDate DebtEntryWidget::nextOccurOn() const
{
	return this->nextOccurOnDtdt->date();
}

Optional<BankName> DebtEntryWidget::bank() const noexcept
{
	return this->borrowedFromCmbbx->bank();
}

Optional<SupportedAccountTypes> DebtEntryWidget::bankAccountType() const noexcept
{
	return this->borrowedFromCmbbx->type();
}

set<BankName> DebtEntryWidget::banks() const noexcept
{
	return this->borrowedFromCmbbx->banks();
}

bool DebtEntryWidget::shouldRemove() const noexcept
{
	return this->removeChckbx->isChecked();
}

bool DebtEntryWidget::isDirty() const noexcept
{
	return this->isDirty_;
}

void DebtEntryWidget::saved()
{
	this->original_ = BudgetSource{this->sourceLndt->text()};
	this->errorMessageLbl->hide();
	this->errorMessageLbl->clear();
	this->isDirty_.flipOff();
}

void DebtEntryWidget::setErrorMessage(const QString& message)
{
	this->errorMessageLbl->setText(message);
	this->errorMessageLbl->show();
	this->isDirty_.flipOn();
}

void DebtEntryWidget::resetDirty()
{
	this->isDirty_.flipOff();
}
