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

#pragma once

#include <QObject>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0))
#  include <memory> /* ::std::unique_ptr */
#else /* < Qt-5.12 */
#  include <QScopedPointer>
#endif /* >= Qt-5.12 */
#include <QSslError>

namespace Json {
	class Int64StringList; /* Forward declaration. */
	class SrvrProfileList; /* Forward declaration. */
	class TagAssignmentCommand; /* Forward declaration. */
	class TagAssignmentList; /* Forward declaration. */
	class TagAssignmentHash; /* Forward declaration. */
	class TagEntryList; /* Forward declaration. */
	class TagIdToAssignmentCountHash; /* Forward declaration. */
	class TagMsgIdList; /* Forward declaration. */
	class TagTextSearchRequestList; /* Forward declaration. */
	class TagTextSearchRequestToIdenfifierHash; /* Forward declaration. */
}
class QNetworkReply; /* Forward declaration. */
class QSslCertificate; /* Forward declaration. */
class QUrl; /* Forward declaration. */

class TagClientPrivate;
/*!
 * @brief Encapsulates connection to tag server.
 */
class TagClient : public QObject {
	Q_OBJECT
	Q_DECLARE_PRIVATE(TagClient)

public:
	enum ErrCode {
		ERR_NO_ERROR = 0, /*!< No error, reply is OK. */
		ERR_NO_CONNECTION, /*!< No active connection to internet. */
		ERR_BAD_REQUEST, /*!< Bad request error. */
		ERR_REPLY, /*!< An reply error. */
		ERR_SERVER_UNAVAILABLE, /*!< Server is out of service. */
		ERR_TIMEOUT, /*!< Connection timed out. */
//		ERR_UNAUTHORIZED, /*!< Authorization error. */
		ERR_UNSPECIFIED /*!< Unspecified error. */
	};

	/*!
	 * @brief Constructor.
	 */
	TagClient(void);

	/*!
	 * @brief Destructor.
	 */
	~TagClient(void);

	/*!
	 * @brief Set server base URL.
	 *
	 * @note Only HTTPS connections are allowed.
	 *
	 * @param[in] url Server base URL (e.g. 'https://localhost').
	 */
	void setBaseUrl(const QUrl &url);

	/*!
	 * @brief Set server WebSocket URL.
	 *
	 * @param[in] url Server WebSocket URL (e.g. 'wss://localhost').
	 */
	void setWebSockUrl(const QUrl &url);

	/*!
	 * @brief Set server CA certificate.
	 *
	 * @param[in] cert CA certificate to be used to validate the server certificate.
	 */
	void setCaCertificate(const QSslCertificate &cert);

	/*!
	 * @brief Set server communication timeout.
	 *
	 * @param[in] msec Number of milliseconds, must be > 0.
	 */
	void setCommunicationTimeout(int msec);

	/*!
	 * @brief Set keep alive timer period.
	 *     The active connection is then periodically queried.
	 *
	 * @param[in] msec Number of milliseconds, must be > 0.
	 *                 Zero value disables the timer.
	 */
	void setKeepAlivePeriod(int msec);

	/*!
	 * @brief Set first delay after connection loss.
	 *
	 * @param[in] msec Number of milliseconds, must be > 0.
	 *                 Zero value disables the timer.
	 */
	void setReconnectDelay(int msec);

	/*!
	 * @brief Set reconnection timer period.
	 *     The aborted connection is then periodically tried being re-established.
	 *
	 * @param[in] msec Number of milliseconds, must be > 0.
	 *                 Zero value disables the timer.
	 */
	void setReconnectPeriod(int msec);

	/*!
	 * @brief Connects to the server using the provided login credentials.
	 *
	 * @param[in] username Account username.
	 * @param[in] pwd Account password.
	 * @return True when connected successfully,
	 *     false on any error.
	 */
	bool netConnectUsernamePwd(const QString &username, const QString &pwd);

	/*!
	 * @brief Query connection.
	 *
	 * @return True when connection to server is established and active,
	 *     false on any error.
	 */
	bool isConnected(void);

	/*!
	 * @brief Disconnect from the server.
	 *
	 * @note The connection is always considered to be terminated after
	 *     calling this method.
	 *
	 * @return True if served acknowledges the connection termination,
	 *     false if communication with the server could not be established.
	 */
	bool netDisconnect(void);

	/*!
	 * @brief Query available user profiles.
	 *
	 * @param[out] profiles List of available user profiles.
	 * @return True on success,
	 *     false on any error.
	 */
	bool listProfiles(Json::SrvrProfileList &profiles);

	/*!
	 * @brief Change/set the user profile on the server.
	 *
	 * @param[in] profileId Profile identifier.
	 * @return True on success,
	 *     false on any error.
	 */
	bool selectProfile(qint64 profileId);

	/*!
	 * @brief Insert new tags into database file.
	 *
	 * @note Emits tagsInserted() when new tags inserted.
	 *
	 * @param[in] entries Tag entries. The entry identifier values are ignored.
	 * @return True on success, false on any error.
	 */
	bool insertTags(const Json::TagEntryList &entries);

	/*!
	 * @brief Update tags in database file.
	 *
	 * @note Emits tagsUpdated() when tag updated.
	 *
	 * @param[in] entries List of entries. Id values must be set to proper
	 *                    values.
	 * @return True on success, false on any error.
	 */
	bool updateTags(const Json::TagEntryList &entries);

	/*!
	 * @brief Delete tags from database file.
	 *
	 * @note Emits tagsDeleted() when tag deleted.
	 *
	 * @param[in] ids List of tag identifiers.
	 * @return True on success, false on any error.
	 */
	bool deleteTags(const Json::Int64StringList &ids);

	/*!
	 * @brief Get tag data from database file.
	 *
	 * @param[in] ids List of tag identifiers.
	 * @param[out] entries List of entries.
	 * @return True on success, false on any error.
	 */
	bool getTagData(const Json::Int64StringList &ids,
	    Json::TagEntryList &entries);

	/*!
	 * @brief Get all tags from database file.
	 *
	 * @param[out] entries List of entries.
	 * @return True on success, false on any error.
	 */
	bool getAllTags(Json::TagEntryList &entries);

	/*!
	 * @brief Get numbers of assignments of given tags.
	 *
	 * @param[in] ids List of tag identifiers.
	 * @param[out] assignmentCounts Numbers of messages the tags are
	 *                              assigned to. Empty map on any error.
	 * @return Error code.
	 */
	bool getTagAssignmentCounts(const Json::Int64StringList &ids,
	    Json::TagIdToAssignmentCountHash &assignmentCounts);

	/*!
	 * @brief Get all tags related to given message.
	 *
	 * @param[in] msgIds List of message identifiers.
	 * @param[out] assignments Found entries are set. If no entries are
	 *                         found for given message then no key and value
	 *                         pair is stored.
	 * @return True on success, false on any error.
	 */
	bool getMessageTags(const Json::TagMsgIdList &msgIds,
	    Json::TagAssignmentHash &assignments);

	/*!
	 * @brief Delete all tags for message identifiers
	 *        in message_tags table.
	 *
	 * @note Emits tagAssignmentChanged() when tag assignment changes.
	 *
	 * @param[in] msgIds List of message identifiers.
	 * @return True on success, false on any error.
	 */
	bool removeAllTagsFromMsgs(const Json::TagMsgIdList &msgIds);

	/*!
	 * @brief Assign existing tags to messages.
	 *
	 * @note Emits tagAssignmentChanged() when tag assignment changes.
	 *
	 * @param[in] assignments Contains tag identifiers to be assigned to
	 *                        respective messages.
	 * @return True on success, false on any error.
	 */
	bool assignTagsToMsgs(
	    const Json::TagAssignmentCommand &assignments);

	/*!
	 * @brief Remove tags from messages.
	 *
	 * @note Emits tagAssignmentChanged() when tag assignment changes.
	 *
	 * @param[in] assignments Contains tag identifiers to be removed from
	 *                        respective messages.
	 * @return True on success, false on any error.
	 */
	bool removeTagsFromMsgs(
	    const Json::TagAssignmentCommand &assignments);

	/*!
	 * @brief Get message IDs related to tags containing sought text.
	 *
	 * @param[in] requests List of text and search type entries.
	 * @param[out] responses List of message identifiers associated to requests.
	 * @return True on success, false on any error.
	 */
	bool getMsgIdsContainSearchTagText(
	    const Json::TagTextSearchRequestList &requests,
	    Json::TagTextSearchRequestToIdenfifierHash &responses);

signals:
	/*!
	 * @brief Emitted when some error during communication occurs.
	 *
	 * @param[in] message Message string containing error description.
	 */
	void connectionError(const QString &message);

	/*!
	 * @brief Emitted when (websocket) connected to server.
	 */
	void connected(void);

	/*!
	 * @brief Emitted when (websocket) disconnected from the server.
	 */
	void disconnected(void);

	/*!
	 * @brief Emitted on significant change. All required data should be reloaded.
	 */
	void reset(void);

	/*!
	 * @brief Emitted when new tags have been inserted into the database.
	 *
	 * @param[in] entries Newly created tag entries.
	 */
	void tagsInserted(const Json::TagEntryList &entries);

	/*!
	 * @brief Emitted when tags have been modified in the database.
	 *
	 * @param[in] entries Modified created tag entries.
	 */
	void tagsUpdated(const Json::TagEntryList &entries);

	/*!
	 * @brief Emitted when tags have been deleted from the database.
	 *
	 * @param[in] ids Deleted tag identifiers.
	 */
	void tagsDeleted(const Json::Int64StringList &ids);

	/*!
	 *  @brief Emitted when tag to message assignment has changed.
	 *
	 *  @param[in] assignments List of modified tag assignments.
	 */
	void tagAssignmentChanged(const Json::TagAssignmentList &assignments);

private slots:
	/*!
	 * @brief Handle SSL errors.
	 *
	 * @param[in,out] reply Communication reply.
	 * @param[in] errors Error listing.
	 */
	void handleSslErrors(QNetworkReply *reply,
	    const QList<QSslError> &errors);

	/*!
	 * @brief Called when websocket is connected.
	 *
	 * @note Sends session cookie to the server in order to identify
	 *     the websocket connection with the respective session.
	 */
	void wsConnected(void);

	/*!
	 * @brief Called on websocket SSL errors.
	 *
	 * @note Can be used to ignore SSL errors.
	 *
	 * @param[in] errors List of SSL errors.
	 */
	void wsSslErrors(const QList<QSslError> &errors);

	/*!
	 * @brief Called when websocket is disconnected.
	 */
	void wsDisconnected(void);

	/*!
	 * @brief Called when websocket receives text data.
	 *
	 * @param[in] message Text message.
	 */
	void wsTextMessageReceived(const QString &message);

	/*!
	 * @brief Called periodically by the keep-alive timer.
	 */
	void keepAlive(void);

	/*!
	 * @brief Called periodically by the reconnection timer.
	 */
	void reconnect(void);

private:
	TagClient(const TagClient &other);
	TagClient &operator=(const TagClient &other) Q_DECL_NOTHROW;

	/*!
	 * @brief Connects to the server using the already stored login credentials.
	 *
	 * @return True when connected successfully,
	 *     false on any error.
	 */
	bool netConnect(void);

	/*!
	 * @brief Send request to server. Obtain the response.
	 *
	 * @param[in] endPoint End point name.
	 * @param[in] requestData Data to be sent.
	 * @param[out] replyData Data from the reply (may be empty).
	 * @return Error code.
	 */
	enum ErrCode communicate(const QString &endPoint,
	    const QByteArray &requestData, QByteArray &replyData);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0))
	::std::unique_ptr<TagClientPrivate> d_ptr;
#else /* < Qt-5.12 */
	QScopedPointer<TagClientPrivate> d_ptr;
#endif /* >= Qt-5.12 */
};
