/*
 * Copyright (C) 2014-2024 CZ.NIC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include "src/global.h"
#include "src/io/account_db.h"
#include "src/io/account_shadow_helper.h"
#include "src/settings/accounts.h"
#include "ui_dlg_create_account.h"

bool ShadowHelper::hasListDownloadPrivileges(const AcntId &acntId)
{
	const QString acntDbKey(AccountDb::keyFromLogin(acntId.username()));
	if (GlobInstcs::accntDbPtr->dbId(acntDbKey).isEmpty()) {
		/* No account information could be obtained. */
		return false;
	}
	Isds::Type::Privileges privileges =
	    GlobInstcs::accntDbPtr->userPrivileges(acntDbKey);

	return privileges & Isds::Type::PRIVIL_VIEW_INFO;
}

/*!
 * @brief Must be able to download message lists and not to download messages.
 *
 * @param[in] acntId Account identifier.
 * @return True if requirements met.
 */
static
bool hasUsableBackgroundPrivileges(const AcntId &acntId)
{
	const QString acntDbKey(AccountDb::keyFromLogin(acntId.username()));
	if (GlobInstcs::accntDbPtr->dbId(acntDbKey).isEmpty()) {
		/* No account information could be obtained. */
		return false;
	}
	Isds::Type::Privileges privileges =
	    GlobInstcs::accntDbPtr->userPrivileges(acntDbKey);

	if (privileges &
	    (Isds::Type::PRIVIL_READ_NON_PERSONAL | Isds::Type::PRIVIL_READ_ALL | Isds::Type::PRIVIL_READ_VAULT)) {
		return false;
	}
	if (!(privileges & Isds::Type::PRIVIL_VIEW_INFO)) {
		return false;
	}

	return true;
}

/*!
 * @brief Whether credentials are suitable for background usage.
 *
 * @param[in] acntId Account identifier.
 * @return False in insufficient.
 */
static
bool usableBackgroundCredentials(const AcntData &acntData)
{
	return (AcntSettings::LIM_UNAME_PWD == acntData.loginMethod()) &&
	    acntData.rememberPwd() && (!acntData.password().isEmpty());
}

bool ShadowHelper::isUsableBackgroundAccount(const AcntId &acntId,
    const AccountsMap &shadowAccounts)
{
	if (Q_UNLIKELY(!acntId.isValid())) {
		Q_ASSERT(0);
		return false;
	}

	if (Q_UNLIKELY(!shadowAccounts.acntIds().contains(acntId))) {
		Q_ASSERT(0);
		return false;
	}

	return hasUsableBackgroundPrivileges(acntId) &&
	    usableBackgroundCredentials(shadowAccounts.acntData(acntId));
}

QList<AcntId> ShadowHelper::usableBackgroundAccounts(const AcntId &rAcntId,
    const AccountsMap &regularAccounts, const AccountsMap &shadowAccounts)
{
	if (Q_UNLIKELY(!rAcntId.isValid())) {
		Q_ASSERT(0);
		return QList<AcntId>();
	}

	if (Q_UNLIKELY(!regularAccounts.keys().contains(rAcntId))) {
		Q_ASSERT(0);
		return QList<AcntId>();
	}

	QList<AcntId> possibleAcntIds;
	foreach (const QString &key, GlobInstcs::accntDbPtr->sameBoxKeys(
	    AccountDb::keyFromLogin(rAcntId.username()))) {
		QString username(AccountDb::loginFromKey(key));
		if (Q_UNLIKELY(username.isEmpty())) {
			continue;
		}
		const AcntId acntId(username, rAcntId.testing());
		if (shadowAccounts.acntIds().contains(acntId)) {
			possibleAcntIds.append(acntId);
		}
	}

	QList<AcntId> shadowAcntIds;
	foreach (const AcntId &acntId, possibleAcntIds) {
		if (isUsableBackgroundAccount(acntId, shadowAccounts)) {
			shadowAcntIds.append(acntId);
		}
	}

	return shadowAcntIds;
}

QList<AcntId> ShadowHelper::availableForegroundAccounts(const AcntId &sAcntId,
    const AccountsMap &regularAccounts, const AccountsMap &shadowAccounts)
{
	if (Q_UNLIKELY(!sAcntId.isValid())) {
		Q_ASSERT(0);
		return QList<AcntId>();
	}

	if (Q_UNLIKELY(!shadowAccounts.keys().contains(sAcntId))) {
		Q_ASSERT(0);
		return QList<AcntId>();
	}

	if (!isUsableBackgroundAccount(sAcntId, shadowAccounts)) {
		/* This shadow account cannot be used for background operations. */
		return QList<AcntId>();
	}

	QList<AcntId> regularAcntIds;
	foreach (const QString &key, GlobInstcs::accntDbPtr->sameBoxKeys(
	    AccountDb::keyFromLogin(sAcntId.username()))) {
		QString username(AccountDb::loginFromKey(key));
		if (Q_UNLIKELY(username.isEmpty())) {
			continue;
		}
		const AcntId acntId(username, sAcntId.testing());
		if (regularAccounts.acntIds().contains(acntId)) {
			regularAcntIds.append(acntId);
		}
	}

	return regularAcntIds;
}
