/*
 * 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.
 */

#pragma once

#include <QDateTime>
#include <QList>
#include <QMap>
#include <QMutex>
#include <QObject>
#include <QPair>
#include <QReadWriteLock>
#include <QString>

namespace Isds {
	/* Forward class declaration. */
	class Session;
}

/*!
 * @brief Container holding context structures of libdatovka.
 */
class IsdsSessions : public QObject {
	Q_OBJECT
public:
	/*!
	 * @brief A hint in which state the session is.
	 */
	enum SessionState {
		SESSION_UNKNOWN = -1, /*!< Undefined value. */
		SESSION_CLEAN = 0, /*!< Clean session, before first login. */
		SESSION_LOGGED_IN = 1, /*!< Session has been used to perform a successful login. */
		SESSION_TERMINATING = 2 /*!< Session is terminating. */
	};

	/*!
	 * @brief Constructor.
	 *
	 * @note Calls Isds::init().
	 */
	IsdsSessions(void);

	/*!
	 * @brief Destructor.
	 *
	 * @note Calls Isds::cleanup().
	 */
	~IsdsSessions(void);

	/*!
	 * @brief Check whether username has a non-terminated session.
	 *
	 * @param[in] username Username identifying the session.
	 * @return True if session exists, false else.
	 */
	bool holdsSession(const QString &username) const;

	/*!
	 * @brief Obtain associated non-terminated session.
	 *
	 * @param[in] username Username identifying the session.
	 * @return Non-null pointer if session exists.
	 */
	Isds::Session *session(const QString &username) const;

	/*!
	 * @brief Obtain creation time of non-terminated session.
	 *
	 * @param[in] username Username identifying the session.
	 * @return Valid date time value if session exists.
	 */
	QDateTime creationTime(const QString &username) const;

	/*!
	 * @brief Obtain session state of non-terminated session.
	 *
	 * @param[in] username Username identifying the session.
	 * @return SESSION_CLEAN or SESSION_LOGGED_IN for non-terminated sessions,
	 *     SESSION_UNKNOWN if non-terminated session doesn't exist.
	 */
	enum SessionState sessionState(const QString &username) const;

	/*!
	 * @brief Ping ISDS. Test whether connection is active.
	 *
	 * @param[in] username Username identifying the session.
	 * @return True if communication with ISDS is established and working,
	 *     false on any error.
	 */
	bool isConnectedToIsds(const QString &username) const;

	/*!
	 * @brief Creates new session.
	 *
	 * @param[in] username Username identifying the newly created session.
	 * @param[in] connectionTimeoutMs Connection timeout in milliseconds.
	 * @return Pointer to new session or Q_NULLPTR on failure.
	 */
	Isds::Session *createCleanSession(const QString &username,
	    unsigned int connectionTimeoutMs);

	/*!
	 * @brief Set time-out in milliseconds to session associated to
	 *     username.
	 *
	 * @param[in] username Username identifying the newly created session.
	 * @param[in] timeoutMs Connection timeout in milliseconds.
	 * @return True on success.
	 */
	bool setSessionTimeout(const QString &username, unsigned int timeoutMs);

	/*!
	 * @brief Notify the container that a successful login has been performed.
	 *     The session state is changed to SESSION_LOGGED_IN.
	 *
	 * @param[in] username Username identifying the session.
	 */
	bool setLoggedIn(const QString &username);

	/*!
	 * @brief Remove session for username.
	 *
	 * @param[in] username Username identifying the session.
	 * @return True if non-terminated session exists and has been removed,
	 *     false otherwise.
	 */
	bool quitSession(const QString &username);

	/*!
	 * @brief remove all sessions.
	 *
	 * @return True if any non-terminated session exists and has been removed,
	 *     false otherwise.
	 */
	bool quitAllSessions(void);

	/*!
	 * @brief Return the number of active (non-terminating) sessions.
	 *
	 * @return Number of active non-terminating sessions.
	 */
	int nowActive(void) const;

Q_SIGNALS:
	/*!
	 * @brief Notifies that a session has been created.
	 *
	 * @param[in] username Username identifying the session.
	 * @param[in] nowActive Number of active sessions after the session has been added.
	 */
	void addedSession(const QString &username, int nowActive);

	/*!
	 * @brief Notifies that a session has been quitted.
	 *
	 * @param[in] username Username identifying the session.
	 * @param[in] nowActive Number of active sessions after the session has been removed.
	 */
	void removedSession(const QString &username, int nowActive);

private:
	mutable QReadWriteLock m_lock; /*!< Read/write mutual exclusion. */
	mutable QMutex m_terminatingLock; /*!< Mutual exclusion for terminating sessions container. */

	/*!
	 * @brief Session container envelope.
	 *
	 * Contains additional information to stored sessions.
	 */
	class SessionEnvelope {
	public:
		SessionEnvelope(void)
		    : sessionPtr(Q_NULLPTR), creationTime(),
		    sessionState(SESSION_UNKNOWN)
		{ }

		SessionEnvelope(const SessionEnvelope &other)
		    : sessionPtr(other.sessionPtr),
		    creationTime(other.creationTime),
		    sessionState(other.sessionState)
		{ }
#ifdef Q_COMPILER_RVALUE_REFS
		SessionEnvelope(SessionEnvelope &&other) Q_DECL_NOEXCEPT
		    : sessionPtr(other.sessionPtr),
		    creationTime(::std::move(other.creationTime)),
		    sessionState(other.sessionState)
		{ }
#endif /* Q_COMPILER_RVALUE_REFS */

		SessionEnvelope(Isds::Session *s, const QDateTime &t, enum SessionState st)
		    : sessionPtr(s), creationTime(t), sessionState(st)
		{ }

		SessionEnvelope &operator=(const SessionEnvelope &other) Q_DECL_NOTHROW
		{
			sessionPtr = other.sessionPtr;
			creationTime = other.creationTime;
			sessionState = other.sessionState;

			return *this;
		}
#ifdef Q_COMPILER_RVALUE_REFS
		SessionEnvelope &operator=(SessionEnvelope &&other) Q_DECL_NOTHROW
		{
			::std::swap(sessionPtr, other.sessionPtr);
			creationTime = ::std::move(other.creationTime);
			::std::swap(sessionState, other.sessionState);

			return *this;
		}
#endif /* Q_COMPILER_RVALUE_REFS */

		Isds::Session *sessionPtr; /*!< Session pointer. */
		QDateTime creationTime; /*!< Time when the session has been created. */
		enum SessionState sessionState; /*!< Session state. */
	};

	QMap<QString, SessionEnvelope> m_sessions; /*!< Maps usernames to sessions. */
	QList< QPair<QString, SessionEnvelope> > m_terminatingSessions; /*!< Holds sessions to be terminated. */
};
