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

#include <QFile>
#include <QFileInfo>

#include "src/datovka_shared/log/log.h"
#include "src/io/sqlite/delayed_access_db.h"

/* Null objects - for convenience. */
static const QSqlDatabase nullSqlDatabase;

DelayedAccessSQLiteDb::DelayedAccessSQLiteDb(const QString &connectionName)
    : QObject(Q_NULLPTR),
    SQLiteDb(connectionName),
    m_fileName(),
    m_flags(SQLiteDb::NO_OPTIONS)
{
}

QString DelayedAccessSQLiteDb::fileName(void) const
{
	return m_fileName;
}

bool DelayedAccessSQLiteDb::beginTransaction(void)
{
	if (Q_UNLIKELY(!_accessDb())) {
		return false;
	}

	return SQLiteDb::beginTransaction();
}

bool DelayedAccessSQLiteDb::savePoint(const QString &savePointName)
{
	if (Q_UNLIKELY(!_accessDb())) {
		return false;
	}

	return SQLiteDb::savePoint(savePointName);
}

bool DelayedAccessSQLiteDb::checkDb(bool quick)
{
	if (Q_UNLIKELY(!_accessDb())) {
		return false;
	}

	return SQLiteDb::checkDb(quick);
}

bool DelayedAccessSQLiteDb::vacuum(void)
{
	if (Q_UNLIKELY(!_accessDb())) {
		return false;
	}

	return SQLiteDb::vacuum();
}

bool DelayedAccessSQLiteDb::backup(const QString &fileName)
{
	if (Q_UNLIKELY(!_accessDb())) {
		return false;
	}

	return SQLiteDb::backup(fileName);
}

qint64 DelayedAccessSQLiteDb::dbSize(void)
{
	if ((!isOpen()) && (!(m_flags & SQLiteDb::FORCE_IN_MEMORY))
	    && (!m_fileName.isEmpty()) && (m_fileName != memoryLocation)) {
		/*
		 * Not opened, not in memory, seems to have a valid file name.
		 * Fetch size from file system if file exists and is readable.
		 */
		const QFileInfo fi(m_fileName);
		if (fi.exists() && fi.isFile() && fi.isReadable()) {
			return fi.size();
		} else {
			logErrorNL(
			    "Cannot acquire size of file '%s' from file system.",
			    m_fileName.toUtf8().constData());
		}
	}

	if (Q_UNLIKELY(!_accessDb())) {
		return -1;
	}

	return SQLiteDb::dbSize();
}

bool DelayedAccessSQLiteDb::copyDb(const QString &newFileName,
    enum SQLiteDb::OpenFlag flag)
{
	if (Q_UNLIKELY(!_accessDb())) {
		return false;
	}

	if (SQLiteDb::copyDb(newFileName, flag)) {
		m_fileName = newFileName;
		m_flags = flag;
		return true;
	}

	return false;
}

bool DelayedAccessSQLiteDb::openDb(const QString &fileName,
     SQLiteDb::OpenFlags flags)
{
	if (Q_UNLIKELY((!(flags & SQLiteDb::FORCE_IN_MEMORY)) && fileName.isEmpty())) {
		Q_ASSERT(0);
		return false;
	}
	if (Q_UNLIKELY((!(flags & SQLiteDb::FORCE_IN_MEMORY)) && (fileName == memoryLocation))) {
		Q_ASSERT(0);
		return false;
	}

	/* A database in memory is opened immediately. */
	if (flags & SQLiteDb::FORCE_IN_MEMORY) {
		logInfoNL("Opening connection '%s' to database file '%s'.",
		    m_db.connectionName().toUtf8().constData(),
		    fileName.toUtf8().constData());
		const bool ret = SQLiteDb::openDb(fileName, flags);
		if (ret) {
			m_fileName = memoryLocation; /* Don't store fileName.*/
			m_flags = flags;
			Q_EMIT opened(m_fileName);
		} else {
			m_fileName.clear();
			m_flags = SQLiteDb::NO_OPTIONS;
		}
		return ret;
	}

	/* Delay the opening of the database file. */
	logInfoNL(
	    "Delaying the opening of connection '%s' to database file '%s'.",
	    m_db.connectionName().toUtf8().constData(),
	    fileName.toUtf8().constData());
	m_fileName = fileName;
	m_flags = flags;
	return true;
}

/*!
 * @brief Move/rename file.
 *
 * @param[in] src Source location.
 * @param[in] dst Destination location.
 * @return True on success.
 */
static
bool moveFile(const QString &src, const QString &dst)
{
	if (Q_UNLIKELY(QFileInfo(dst).exists())) {
		logErrorNL(
		    "Cannot rename file '%s' to '%s' because target already exists.",
		    src.toUtf8().constData(), dst.toUtf8().constData());
	}

	if (!QFileInfo(src).exists()) {
		/* Don't copy anything. */
		return true;
	}

	return QFile(src).rename(dst);
}

bool DelayedAccessSQLiteDb::renameDb(const QString &newConnectionName,
    const QString &newFileName)
{
	if (Q_UNLIKELY(newConnectionName.isEmpty() || newFileName.isEmpty())) {
		Q_ASSERT(0);
		return false;
	}

	if (Q_UNLIKELY(m_flags & SQLiteDb::FORCE_IN_MEMORY)) {
		Q_ASSERT(0);
		return false;
	}

	if (Q_UNLIKELY((m_fileName == memoryLocation) || m_fileName.isEmpty())) {
		Q_ASSERT(0);
		return false;
	}

	bool opened = isOpen();
	if (opened) {
		closeDb();
	}
	if (Q_UNLIKELY(isOpen())) {
		Q_ASSERT(0);
		return false;
	}

	int ret = moveFile(m_fileName, newFileName);
	if (ret) {
		m_fileName = newFileName;
	}

	if (opened) {
		return _accessDb();
	}

	return true;
}

bool DelayedAccessSQLiteDb::isOpen(void) const
{
	return m_db.isOpen();
}

const QSqlDatabase &DelayedAccessSQLiteDb::accessDb(void)
{
	if (Q_UNLIKELY(!_accessDb())) {
		/*
		 * Cannot call Q_ASSERT(0) here.
		 * The application mustn't crash when attempting to access
		 * corrupt database.
		 */
		return nullSqlDatabase;
	}

	return m_db;
}

bool DelayedAccessSQLiteDb::_accessDb(void)
{
	if (Q_UNLIKELY(!isOpen())) {
		const QByteArray connName(m_db.connectionName().toUtf8());
		const char *cCName = connName.constData();
		if (Q_UNLIKELY(m_fileName.isEmpty())) {
			logErrorNL(
			    "Missing file name to unopened database '%s'.",
			    cCName);
			Q_ASSERT(0);
			return false;
		}
		const QByteArray fileName(m_fileName.toUtf8());
		const char *cFileName = fileName.constData();
		logInfoNL("Opening connection '%s' to database file '%s'.",
		    cCName, cFileName);
		if (Q_UNLIKELY(!SQLiteDb::openDb(m_fileName, m_flags))) {
			logErrorNL("Cannot open database '%s'.", cFileName);
			Q_EMIT openingFailed(m_fileName);
			return false;
		}
		Q_EMIT opened(m_fileName);
	}

	return true;
}
