/*
 * Copyright (C) 2014-2022 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 <QList>
#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 "src/datovka_shared/io/sqlite/db_single.h"
#include "src/datovka_shared/json/object.h"

class AcntId; /* Forward declaration. */
namespace Json {
	class Int64StringList; /* Forward declaration. */
	class TagAssignmentCommand; /* Forward declaration. */
	class TagAssignmentHash; /* Forward declaration. */
	class TagAssignmentList; /* Forward declaration. */
	class TagEntryList; /* Forward declaration. */
	class TagIdToAssignmentCountHash; /* Forward declaration. */
	class TagIdToMsgIdListHash; /* Forward declaration. */
	class TagMsgIdList; /* Forward declaration. */
	class TagTextSearchRequestList; /* Forward declaration. */
	class TagTextSearchRequestToIdenfifierHash; /* Forward declaration. */
}

namespace Json {
	class TagDbInfoPrivate;
	/*!
	 * @brief Encapsulates information about the tag database.
	 */
	class TagDbInfo : public Object {
		Q_DECLARE_PRIVATE(TagDbInfo)
	public:
		TagDbInfo(void);
		TagDbInfo(const TagDbInfo &other);
#ifdef Q_COMPILER_RVALUE_REFS
		TagDbInfo(TagDbInfo &&other) Q_DECL_NOEXCEPT;
#endif /* Q_COMPILER_RVALUE_REFS */
		~TagDbInfo(void);

		TagDbInfo &operator=(const TagDbInfo &other) Q_DECL_NOTHROW;
#ifdef Q_COMPILER_RVALUE_REFS
		TagDbInfo &operator=(TagDbInfo &&other) Q_DECL_NOTHROW;
#endif /* Q_COMPILER_RVALUE_REFS */

		bool operator==(const TagDbInfo &other) const;
		bool operator!=(const TagDbInfo &other) const;

		friend void swap(TagDbInfo &first, TagDbInfo &second) Q_DECL_NOTHROW;

		bool isNull(void) const;

		bool isValid(void) const;

		/* format version major */
		int formatVersionMajor(void) const;
		void setFormatVersionMajor(int maj);
		/* format version minor */
		int formatVersionMinor(void) const;
		void setFormatVersionMinor(int min);

		static
		TagDbInfo fromJson(const QByteArray &json, bool *ok = Q_NULLPTR);
		static
		TagDbInfo fromJsonVal(const QJsonValue &jsonVal, bool *ok = Q_NULLPTR);

		virtual
		bool toJsonVal(QJsonValue &jsonVal) const Q_DECL_OVERRIDE;

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

	void swap(TagDbInfo &first, TagDbInfo &second) Q_DECL_NOTHROW;
}

/*!
 * @brief Encapsulates tag database.
 */
class TagDb : public QObject, public SQLiteDbSingle {
	Q_OBJECT

public:
	/* Use parent class constructor. */
	using SQLiteDbSingle::SQLiteDbSingle;

	/*!
	 * @brief Get information about the database.
	 *
	 * @param[out] info Database information.
	 * @return True on success, false on any error.
	 */
	bool getDbInfo(Json::TagDbInfo &info) const;

	/*!
	 * @brief Update database information.
	 *
	 * @param[in] info Database information.
	 * @return True on success, false on any error.
	 */
	bool updateDbInfo(const Json::TagDbInfo &info);

	/*!
	 * @brief Converts old username-dependent format into a new one which
	 *     does not distinguish between usernames.
	 *
	 * @note Cannot just use assureConsistency() because account data are
	 *     needed.
	 *
	 * @param[in] regularAcntIds List of account identifiers.
	 */
	bool convertAccountIdentifiersToTestEnvFlag(
	    const QList<AcntId> &regularAcntIds);

	/*!
	 * @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(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) const;

	/*!
	 * @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) const;

	/*!
	 * @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) const;

	/*!
	 * @brief Get message identifiers with with assigned tags.
	 *
	 * @param[in] ids List of tag identifiers.
	 * @param[out] assignments Lists of messages which the respective tags
	 *                         are assigned to. Empty map on any error.
	 * @return Error code.
	 */
	bool getTagMessages(const Json::Int64StringList &ids,
	    Json::TagIdToMsgIdListHash &assignments) const;

	/*!
	 * @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) const;

	/*!
	 * @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) const;

signals:
	/*!
	 * @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);

protected:
	/*!
	 * @brief Returns list of tables.
	 *
	 * @return List of pointers to tables.
	 */
	virtual
	QList<class SQLiteTbl *> listOfTables(void) const Q_DECL_OVERRIDE;

	/*!
	 * @brief Enables foreign key support.
	 *
	 * @note Foreign key functionality is not enabled by default at runtime.
	 *     https://sqlite.org/foreignkeys.html
	 *
	 * @return True on success.
	 */
	virtual
	bool enableFunctionality(void) Q_DECL_OVERRIDE;
};
