/*
 * Copyright (C) 2014-2026 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 <QMutexLocker>
#include <QReadLocker>
#include <QWriteLocker>

#include "src/common.h"
#include "src/datovka_shared/isds/error.h"
#include "src/datovka_shared/log/log.h"
#include "src/global.h"
#include "src/io/imports.h"
#include "src/io/isds_sessions.h"
#include "src/isds/initialisation.h"
#include "src/isds/services.h"
#include "src/isds/session.h"
#include "src/models/accounts_model.h"
#include "src/settings/prefs_specific.h"

IsdsSessions::IsdsSessions(void)
    : QObject(),
    m_lock(),
    m_terminatingLock(),
    m_sessions(),
    m_terminatingSessions()
{
	/* Initialise libdatovka. */
	Isds::init();
}

IsdsSessions::~IsdsSessions(void)
{
	/* Free all contexts. */
	{
		QWriteLocker locker(&m_lock);
		for (const SessionEnvelope &se : m_sessions) {
			delete se.sessionPtr;
		}
		m_sessions.clear();
	}
	{
		QMutexLocker locker(&m_terminatingLock);
		for (QPair<QString, SessionEnvelope> &pair : m_terminatingSessions) {
			delete pair.second.sessionPtr;
		}
		m_terminatingSessions.clear();
	}

	Isds::cleanup();
}

bool IsdsSessions::holdsSession(const QString &username) const
{
	QReadLocker locker(&m_lock);
	return Q_NULLPTR != m_sessions.value(username, SessionEnvelope()).sessionPtr;
}

Isds::Session *IsdsSessions::session(const QString &username) const
{
	QReadLocker locker(&m_lock);
	return m_sessions.value(username, SessionEnvelope()).sessionPtr;
}

QDateTime IsdsSessions::creationTime(const QString &username) const
{
	QReadLocker locker(&m_lock);
	return m_sessions.value(username, SessionEnvelope()).creationTime;
}

enum IsdsSessions::SessionState IsdsSessions::sessionState(const QString &username) const
{
	QReadLocker locker(&m_lock);
	return m_sessions.value(username, SessionEnvelope()).sessionState;
}

/*!
 * @brief Set time-out in milliseconds to session associated to
 *     username.
 *
 * @param[in] session Session pointer.
 * @param[in] username Username identifying the newly created session.
 * @param[in] timeoutMs Connection timeout in milliseconds.
 * @return True on success.
 */
static inline
bool _setSessionTimeout(Isds::Session *session, const QString &username,
    unsigned int timeoutMs)
{
	if (Q_UNLIKELY(Q_NULLPTR == session)) {
		Q_ASSERT(0);
		return false;
	}

	bool ret = session->setTimeout(timeoutMs);
	if (Q_UNLIKELY(!ret)) {
		logErrorNL("Error setting time-out for username '%s'.",
		    username.toUtf8().constData());
	}

	return ret;
}

bool IsdsSessions::isConnectedToIsds(const QString &username) const
{
	Isds::Session *s = session(username); /* Uses QReadLocker. */
	if (Q_UNLIKELY(Q_NULLPTR == s)) {
		return false;
	}

	Isds::Error pingErr;

	_setSessionTimeout(s, username, ISDS_PING_TIMEOUT_MS);
	pingErr = Isds::Service::dummyOperation(s);
	_setSessionTimeout(s, username,
	    PrefsSpecific::isdsDownloadTimeoutMs(*GlobInstcs::prefsPtr));

	return Isds::Type::ERR_SUCCESS == pingErr.code();
}

Isds::Session *IsdsSessions::createCleanSession(const QString &username,
    unsigned int connectionTimeoutMs)
{
	Isds::Session *session = Q_NULLPTR;
	int numActive = 0;
	{
		QWriteLocker locker(&m_lock);

		/* Username shouldn't exist. */
		if (Q_UNLIKELY(Q_NULLPTR != m_sessions.value(username, SessionEnvelope()).sessionPtr)) {
			Q_ASSERT(0);
			return Q_NULLPTR;
		}

		QDateTime now = QDateTime::currentDateTimeUtc();
		session = Isds::Session::createSession(connectionTimeoutMs);
		if (Q_UNLIKELY(Q_NULLPTR == session)) {
			logErrorNL("Error creating ISDS session for username '%s'.",
			    username.toUtf8().constData());
			return Q_NULLPTR;
		}

		m_sessions.insert(username, SessionEnvelope(session, now, SESSION_CLEAN));
		numActive = m_sessions.size();
	}
	/* Signal is emitted after releasing the lock. */
	Q_EMIT addedSession(username, numActive);
	return session;
}

bool IsdsSessions::setSessionTimeout(const QString &username,
    unsigned int timeoutMs)
{
	Isds::Session *s = session(username); /* Uses QReadLocker. */
	if (Q_UNLIKELY(Q_NULLPTR == s)) {
		Q_ASSERT(0);
		return false;
	}

	return _setSessionTimeout(s, username, timeoutMs);
}

bool IsdsSessions::setLoggedIn(const QString &username)
{
	QWriteLocker locker(&m_lock);

	const SessionEnvelope se = m_sessions.value(username, SessionEnvelope());
	if (Q_NULLPTR != se.sessionPtr) {
		m_sessions[username].sessionState = SESSION_LOGGED_IN;
		return true;
	}

	return false;
}

bool IsdsSessions::quitSession(const QString &username)
{
	/*
	 * Don't delete the session directly because it may still be used in
	 * other threads.
	 */
	SessionEnvelope se;
	int numActive = 0;

	{
		QWriteLocker locker(&m_lock);

		se = m_sessions.value(username, SessionEnvelope());
		if (Q_NULLPTR != se.sessionPtr) {
			m_sessions.remove(username);
			numActive = m_sessions.size();
		}
	}

	if (Q_NULLPTR != se.sessionPtr) {
		/* Signal is emitted after releasing the first lock. */
		Q_EMIT removedSession(username, numActive);

		QMutexLocker locker(&m_terminatingLock);

		/*
		 * Just append terminating sessions.
		 * TODO -- Implement safe deletion after a cool-down period.
		 */
		se.sessionState = SESSION_TERMINATING;
		m_terminatingSessions.append(
		    QPair<QString, SessionEnvelope>(username, se));

		return true;
	}

	return false;
}

bool IsdsSessions::quitAllSessions(void)
{
	QMap<QString, SessionEnvelope> removedSessions;

	{
		QWriteLocker locker(&m_lock);

		removedSessions = m_sessions;
		m_sessions.clear();
	}

	if (removedSessions.size() > 0) {
		/* Signals are emitted after releaseing the first lock. */
		for (const QString &username : removedSessions.keys()) {
			Q_EMIT removedSession(username, 0);
		}

		QMutexLocker locker(&m_terminatingLock);

		for (const QString &username : removedSessions.keys()) {
			/*
			 * Just append terminating sessions.
			 * TODO -- Implement safe deletion after a cool-down period.
			 */
			m_terminatingSessions.append(
			    QPair<QString, SessionEnvelope>(username,
			        removedSessions.value(username, SessionEnvelope())));
		}
		return true;
	}

	return false;
}

int IsdsSessions::nowActive(void) const
{
	QReadLocker locker(&m_lock);
	return m_sessions.size();
}
