/*
 * 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 <QMainWindow>
#include <QMap>
#include <QSet>
#include <QString>
#include <QThread>
#include <QTimer>

class CorruptMessageDb; /* Forward declaration. */
class MessageDb; /* Forward declaration. */
namespace Isds {
	class Envelope; /* Forward declaration. */
	class Message; /* Forward declaration. */
}

namespace Ui {
	class MWDbRepair;
}

/*!
 * @brief Database data recovery thread.
 */
class RepairThread : public QThread {
	Q_OBJECT

public:
	/*!
	 * @brief Constructor.
	 */
	explicit RepairThread(void);

	/*!
	 * @brief Set source database file path.
	 *
	 * @param[in] srcDbPath File path.
	 */
	void setSrcDbPath(const QString &srcDbPath);

	/*!
	 * @brief Set work directory path.
	 *
	 * @param[in] workDirPath Directory path.
	 */
	void setWorkDirPath(const QString &workDirPath);

	/*!
	 * @brief Set whether to reassemble the message database file.
	 *
	 * @param[in] reassembleDb Whether to reassemble message database.
	 */
	void setReassembleDb(bool reassembleDb);

	/*!
	 * @brief Path to reconstructed database file if created.
	 *
	 * @return Non-null path string if the file was created.
	 */
	const QString &tgtDbPath(void) const;

protected:
	/*!
	 * @brief Starting point of the thread.
	 */
	virtual
	void run(void) Q_DECL_OVERRIDE;

Q_SIGNALS:
	/*!
	 * @brief Emitted during thread runtime.
	 *
	 * @param[in] str Information message.
	 */
	void infoMsg(const QString &str);

	/*!
	 * @brief Emitted during thread runtime.
	 *
	 * @param[in] str Error message.
	 */
	void errorMsg(const QString &str);

private:
	/*!
	 * @brief Extract mssage data and save them to a file into work directory.
	 *
	 * @param[in] cmdb Corrupt message database.
	 * @param[in] dmId Message identifier.
	 * @param[in] messageDirection Specifies received, sent or unknown direction.
	 * @param[in] dmVODZ Specifies whether it is a high-volume message.
	 * @return Path to a created file on success, null string on error.
	 */
	QString extracttMessageFile(CorruptMessageDb &cmdb, qint64 dmId,
	    int messageDirection, bool dmVODZ);

	/*!
	 * @brief Collect envelopes according to supplied message identifiers.
	 *
	 * @param[in] cmdb Corrupt message database.
	 * @param[in] dmIds Message identifiers.
	 * @param[in] knowsVODZ True if corrupt database knows dmVODZ.
	 * @return Map of extracted envelopes corresponding to supplied \a dmIds.
	 */
	QMap<qint64, Isds::Envelope> collectEnvelopes(CorruptMessageDb &cmdb,
	    const QSet<qint64> &dmIds, bool knowsVODZ);

	/*!
	 * @brief Insert envelopes into database.
	 *
	 * @param[in,out] tgtDb Target message database.
	 * @param[in] envelopes Map of envelopes.
	 * @param[in] messageType Specifies received or sent messages.
	 * @return Set of inserted envelope identifiers.
	 */
	QSet<qint64> reinsertEnvelopes(MessageDb &tgtDb,
	    const QMap<qint64, Isds::Envelope> &envelopes, int messageType);

	/*!
	 * @brief Store signed message delivery info into database.
	 *
	 * @param[in,out] tgtDb Target message database.
	 * @param[in] message Message structure.
	 * @param[in] storeRawInDb Whether to store raw data in database file.
	 * @return True on success.
	 */
	bool storeSignedDeliveryInfo(MessageDb &tgtDb,
	    const Isds::Message &message, bool storeRawInDb);

	/*!
	 * @brief Store complete signed message into database.
	 *
	 * @param[in] transaction True to create a transaction.
	 * @param[in] messageType Specifies received or sent messages.
	 * @param[in,out] tgtDb Target message database.
	 * @param[in] message Message structure.
	 * @param[in] storeRawInDb Whether to store raw data in database file.
	 * @return True on success.
	 */
	bool storeSignedMessage(bool transaction, int messageType,
	    MessageDb &tgtDb, const Isds::Message &message, bool storeRawInDb);

	/*!
	 * @brief Insert delivery info from file into database.
	 *
	 * @param[in,out] tgtDb Target message database.
	 * @param[in] infoFilePath Delivery info file path.
	 * @return True on success.
	 */
	bool reinsertDeliveryInfo(MessageDb &tgtDb, const QString &infoFilePath);

	/*!
	 * @brief Insert message from file into database.
	 *
	 * @param[in,out] tgtDb Target message database.
	 * @param[in] msgFilePath Message file path.
	 * @param[in] messageType Specifies received or sent messages.
	 * @return True on success.
	 */
	bool reinsertMessage(MessageDb &tgtDb, const QString &msgFilePath,
	    int messageType);

	QString m_srcDbPath; /*!< Source database path. */
	QString m_workDirPath; /*!< Work directory. */
	bool m_reassembleDb; /*!< Whether to reassemble message database from collected data. */

	QString m_tgtDbPath; /*!< Path to created database file. */
};

/*!
 * @brief Repair database window.
 */
class MWDbRepair : public QMainWindow {
	Q_OBJECT

public:
	/*!
	 * @brief Constructor.
	 *
	 * @param[in] parent Parent widget.
	 */
	explicit MWDbRepair(QWidget *parent = Q_NULLPTR);

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

	static
	bool runDatabaseRepair; /*!< Set to true when database repair should be run. */
	static
	QString passedMessageDbDir; /*!<
	                             * Pass the directory path where to let
	                             * the user open the first file.
	                             */
	static
	QString passedMessageDbFile; /*!<
	                              * Pass the path to selected message database.
	                              * This path is checked for existence.
	                              */

protected:
	/*!
	 * @brief Check if thread is working on the background and show
	 *     a dialogue whether the user wants to close the application.
	 *
	 * @param[in,out] event Close event.
	 */
	virtual
	void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE;

private Q_SLOTS:
	/*!
	 * @brief Stops action and closes the window.
	 */
	void haltRequested(void);

	/*!
	 * @brief Shows the quit app dialogue.
	 */
	void viewAskCloseDlg(void);

	/*!
	 * @brief Quit app dialogue closed.
	 *
	 * @param[in] result Dialogue window closing status.
	 */
	void closedAskCloseDlg(int result);

	/*!
	 * @brief Load a message database file.
	 */
	void loadMessageDbFile(void);

	/*!
	 * @brief Select work directory.
	 */
	void selectWorkDirectory(void);

	/*!
	 * @brief @brief Check input fields' sanity and activate run button.
	 */
	void checkInputFields(void);

	/*!
	 * @brief Show a message in the text area.
	 *
	 * @param[in] str Message string.
	 */
	void showInfo(const QString &str);

	/*!
	 * @brief Show an error message in the text area.
	 *
	 * @note Error prefix is added.
	 *
	 * @param[in] str Error message string.
	 */
	void showError(const QString &str);

	/*!
	 * @brief Starts the data recovery thread.
	 */
	void runRepair(void);

	/*!
	 * @brief Re-enables controls after thread finishes.
	 */
	void finishedRepair(void);

	/*!
	 * @brief Run database replacement.
	 */
	void replaceCorrupt(void);

private:
	/*!
	 * @brief Load a message database file.
	 *
	 * @param[in] fileName Path to file.
	 */
	void loadAndCheckMessageDbFile(QString fileName);

	/*!
	 * @brief Connects top menu bar actions to appropriate slots.
	 */
	void topMenuConnectActions(void) const;

private:
	Ui::MWDbRepair *m_ui; /*!< UI generated from UI file. */

	QTimer m_timerCheckReqHalt;

	QDialog *m_askCloseDlg; /*!< Non-null if ask cancel task dialogue is active. */

	RepairThread *m_repairThread; /*!< Tries to recover stored data. */
};
