/*
 * Copyright (C) 2014-2019 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 <QSettings>

#include "src/datovka_shared/settings/account_container.h"

template <class T>
void AcntSettingsMap<T>::loadFromSettings(const QString &confDir,
    const QSettings &settings)
{
	/* Clear present rows. */
	this->clear();

	T itemSettings;

	/* For all credentials. */
	foreach (const QString &group, sortedCredentialGroups(settings)) {
		itemSettings.clear();

		itemSettings.loadFromSettings(confDir, settings, group);

		/* Associate map with item node. */
		Q_ASSERT(!itemSettings.userName().isEmpty());
		AcntId acntId(itemSettings.userName(), itemSettings.isTestAccount());
		Q_ASSERT(acntId.isValid());
		this->operator[](acntId) = itemSettings;
	}
}

template <class T>
void AcntSettingsMap<T>::decryptAllPwds(const QString &pinVal)
{
	for (typename AcntSettingsMap<T>::iterator it = this->begin();
	     it != this->end(); ++it) {
		it->decryptPassword(pinVal);
	}
}

template <class T>
AcntId AcntSettingsMap<T>::acntIdFromUsername(const QString &username) const
{
	foreach (const AcntId &acntId, AcntSettingsMap<T>::keys()) {
		if (acntId.username() == username) {
			return acntId;
		}
	}

	return AcntId();
}

/*!
 * @brief Used for sorting credentials.
 *
 * @param[in] s1  credentials[0-9]*
 * @param[in] s2  credentials[0-9]*
 * @return True if s1 comes before s2.
 *
 * @note The number is taken by its value rather like a string of characters.
 * cred < cred1 < cred2 < ... < cred10 < ... < cred100 < ...
 */
static
bool credentialsLessThan(const QString &s1, const QString &s2)
{
	QRegExp trailingNumRe("(.*[^0-9]+)*([0-9]+)");
	QString a1, a2;
	int n1, n2;
	int pos;

	pos = trailingNumRe.indexIn(s1);
	if (pos > -1) {
		a1 = trailingNumRe.cap(1);
		n1 = trailingNumRe.cap(2).toInt();
	} else {
		a1 = s1;
		n1 = -1;
	}

	pos = trailingNumRe.indexIn(s2);
	if (pos > -1) {
		a2 = trailingNumRe.cap(1);
		n2 = trailingNumRe.cap(2).toInt();
	} else {
		a2 = s2;
		n2 = -1;
	}

	return (a1 != a2) ? (a1 < a2) : (n1 < n2);
}

template <class T>
QStringList AcntSettingsMap<T>::sortedCredentialGroups(const QSettings &settings)
{
	const QRegExp credRe(CredNames::creds + ".*");

	QStringList credentialList;
	/* Get list of credentials. */
	foreach (const QString &group, settings.childGroups()) {
		/* Matches regular expression. */
		if (credRe.exactMatch(group)) {
			credentialList.append(group);
		}
	}

	/* Sort the credentials list. */
	qSort(credentialList.begin(), credentialList.end(), credentialsLessThan);

	return credentialList;
}

template <class T>
QString AcntSettingsMap<T>::credentialGroupName(int num)
{
	if (Q_UNLIKELY(num < 1)) {
		Q_ASSERT(0);
	}

	if (num != 1) {
		return CredNames::creds + QString::number(num);
	} else {
		return CredNames::creds;
	}
}

/*!
 * @brief Get the maximal number of the credentials group.
 *
 * @param[in] credentialGroups Group list.
 * @return Number of the last credentials group.
 */
static
int maxCredentialNum(const QStringList &credentialGroups)
{
	const QRegExp credRe(CredNames::creds + ".*");

	int num = 0;
	foreach (const QString &group, credentialGroups) {
		/* Must match regular expression. */
		if (Q_UNLIKELY(!credRe.exactMatch(group))) {
			Q_ASSERT(0);
			continue;
		}
		QString numStr(group);
		numStr.replace(CredNames::creds, QString());
		if (numStr.isEmpty()) {
			if (1 > num) {
				num = 1; /* Group 1 has no number. */
			}
		} else {
			bool iOk = false;
			int readNum = numStr.toInt(&iOk);
			if (Q_UNLIKELY(!iOk)) {
				Q_ASSERT(0);
				continue;
			}
			if (readNum > num) {
				num = readNum;
			}
		}
	}
	return num;
}

template <class T>
void AcntSettingsMap<T>::addCredentialsTorso(QSettings &settings,
    const QString &accountName, const AcntId &acntId)
{
	if (Q_UNLIKELY(accountName.isEmpty() || (!acntId.isValid()))) {
		Q_ASSERT(0);
		return;
	}

	int credMax = maxCredentialNum(sortedCredentialGroups(settings));

	T acntSettings;

	acntSettings.setAccountName(accountName);
	acntSettings.setUserName(acntId.username());
	acntSettings.setTestAccount(acntId.testing());
	/* Use password login method without stored password. */
	acntSettings.setLoginMethod(T::LIM_UNAME_PWD);
	acntSettings.setRememberPwd(false);

	acntSettings.saveToSettings(QString(), QString(), settings,
	    credentialGroupName(credMax + 1));
}
