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

#include <QFileInfo>

#include "src/io/message_db.h"
#include "src/io/message_db_single.h"

MessageDbSingle::MessageDbSingle(void)
    : m_db(Q_NULLPTR)
{
}

MessageDbSingle::~MessageDbSingle(void)
{
	delete m_db;
}

MessageDbSingle *MessageDbSingle::createNew(const QString &filePath,
    const QString &connectionPrefix)
{
	if (Q_UNLIKELY(filePath.isEmpty())) {
		return Q_NULLPTR;
	}

	if (Q_UNLIKELY(!QFileInfo::exists(filePath))) {
		return Q_NULLPTR;
	}

	QString connectionName(connectionPrefix + "_SINGLE_FILE");

	MessageDb *db = new (::std::nothrow) MessageDb(connectionName);
	if (Q_UNLIKELY(Q_NULLPTR == db)) {
		Q_ASSERT(0);
		return Q_NULLPTR;
	}

	if (Q_UNLIKELY(!db->openDb(filePath, SQLiteDb::CREATE_MISSING))) {
		delete db;
		return Q_NULLPTR;
	}

	MessageDbSingle *dbSingle = new (::std::nothrow) MessageDbSingle();
	if (Q_UNLIKELY(Q_NULLPTR == dbSingle)) {
		delete db;
		return Q_NULLPTR;
	}

	/* Assign database. */
	dbSingle->m_db = db;

	return dbSingle;
}

/* Methods delegated from MessageDb and made public via this class. */

QSet<MsgId> MessageDbSingle::getAllMsgIds(void) const
{
	return m_db->getAllMsgIds();
}

bool MessageDbSingle::isRelevantMsgForImport(qint64 msgId,
    const QString &dbId) const
{
	return m_db->isRelevantMsgForImport(msgId, dbId);
}

int MessageDbSingle::getMessageType(qint64 dmId)
{
	return m_db->getMessageType(dmId);
}

bool MessageDbSingle::insertOrReplaceCompleteMessage(bool storeRawInDb,
    const Isds::Message &msg,
    enum MessageDirection msgDirect, bool verified, bool transaction)
{
	return m_db->insertOrReplaceCompleteMessage(storeRawInDb, msg, msgDirect,
	    verified, transaction);
}

bool MessageDbSingle::insertOrReplaceDeliveryInfoRaw(bool storeRawInDb,
    qint64 dmId, const QByteArray &raw)
{
	return m_db->insertOrReplaceDeliveryInfoRaw(storeRawInDb, dmId, raw);
}
