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

#include <QFileInfo>

#include "src/datovka_shared/log/log.h"
#include "src/io/message_db_set_container.h"

DbContainer::DbContainer(bool onDisk, const QString &connectionPrefix)
    : QObject(Q_NULLPTR),
    QMap<AcntId, MessageDbSet *>(),
    m_onDisk(onDisk),
    m_connectionPrefix(connectionPrefix)
{
}

DbContainer::~DbContainer(void)
{
	QMap<AcntId, MessageDbSet *>::iterator i;

	for (i = this->begin(); i != this->end(); ++i) {
		MessageDbSet *dbSet = i.value();
		/* No need to call disconnect here. */
		//dbSet->disconnect(SIGNAL(opened(QString, bool)),
		//    this, SLOT(watchOpened(QString, bool)));
		//dbSet->disconnect(SIGNAL(changedLocallyRead(QString, bool, QList<MsgId>, bool)),
		//    this, SLOT(watchChangedLocallyRead(QString, bool, QList<MsgId>, bool)));
		//dbSet->disconnect(SIGNAL(changedProcessState(QString, bool, QList<MsgId>, enum MessageDb::MessageProcessState)),
		//    this, SLOT(watchChangedProcessState(QString, bool, QList<MsgId>, enum MessageDb::MessageProcessState)));
		//dbSet->disconnect(SIGNAL(messageInserted(QString, bool, MsgId, int)),
		//    this, SLOT(watchMessageInserted(QString, bool, MsgId, int)));
		//dbSet->disconnect(SIGNAL(messageDataDeleted(QString, bool, MsgId)),
		//    this, SLOT(watchMessageDataDeleted(QString, bool, MsgId)));
		delete dbSet;
	}
}

MessageDbSet *DbContainer::accessOpenedDbSet(const AcntId &acntId) const
{
	if (Q_UNLIKELY(!acntId.isValid())) {
		Q_ASSERT(0);
		return Q_NULLPTR;
	}

	/* Already opened. */
	if (this->find(acntId) != this->end()) {
		return (*this)[acntId];
	}

	return Q_NULLPTR;
}

MessageDbSet *DbContainer::accessDbSet(const QString &locDir,
    const AcntId &acntId, MessageDbSet::Organisation organisation,
    enum MessageDbSet::CreationManner manner)
{
	MessageDbSet *dbSet = accessOpenedDbSet(acntId);
	if (Q_NULLPTR != dbSet) {
		return dbSet;
	}

	dbSet = MessageDbSet::createNew(locDir, acntId.username(),
	    acntId.testing(), organisation, m_onDisk, m_connectionPrefix,
	    manner);
	if (Q_UNLIKELY(Q_NULLPTR == dbSet)) {
		return Q_NULLPTR;
	}

	connect(dbSet, SIGNAL(madeAvailable(QString, bool)),
	    this, SLOT(watchMadeAvailable(QString, bool)));
	connect(dbSet, SIGNAL(opened(QString, bool)),
	    this, SLOT(watchOpened(QString, bool)));
	connect(dbSet, SIGNAL(changedLocallyRead(QString, bool, QList<MsgId>, bool)),
	    this, SLOT(watchChangedLocallyRead(QString, bool, QList<MsgId>, bool)));
	connect(dbSet, SIGNAL(changedProcessState(QString, bool, QList<MsgId>, enum MessageDb::MessageProcessState)),
	    this, SLOT(watchChangedProcessState(QString, bool, QList<MsgId>, enum MessageDb::MessageProcessState)));
	connect(dbSet, SIGNAL(messageInserted(QString, bool, MsgId, int)),
	    this, SLOT(watchMessageInserted(QString, bool, MsgId, int)));
	connect(dbSet, SIGNAL(messageDataDeleted(QString, bool, MsgId)),
	    this, SLOT(watchMessageDataDeleted(QString, bool, MsgId)));

	this->insert(acntId, dbSet);
	emit madeAvailable(acntId);
	return dbSet;
}

bool DbContainer::deleteDbSet(MessageDbSet *dbSet)
{
	if (Q_UNLIKELY(Q_NULLPTR == dbSet)) {
		Q_ASSERT(0);
		return false;
	}

	/* Find entry. */
	QMap<AcntId, MessageDbSet *>::iterator it = this->begin();
	while ((it != this->end()) && (it.value() != dbSet)) {
		++it;
	}
	/* Must exist. */
	if (Q_UNLIKELY(this->end() == it)) {
		Q_ASSERT(0);
		return false;
	}

	/* Remove from container. */
	this->erase(it);

	/* Delete files. */
	dbSet->deleteLocation();

	dbSet->disconnect(SIGNAL(madeAvailable(QString, bool)),
	    this, SLOT(watchMadeAvailable(QString, bool)));
	dbSet->disconnect(SIGNAL(opened(QString, bool)),
	    this, SLOT(watchOpened(QString, bool)));
	dbSet->disconnect(SIGNAL(changedLocallyRead(QString, bool, QList<MsgId>, bool)),
	    this, SLOT(watchChangedLocallyRead(QString, bool, QList<MsgId>, bool)));
	dbSet->disconnect(SIGNAL(changedProcessState(QString, bool, QList<MsgId>, enum MessageDb::MessageProcessState)),
	    this, SLOT(watchChangedProcessState(QString, bool, QList<MsgId>, enum MessageDb::MessageProcessState)));
	dbSet->disconnect(SIGNAL(messageInserted(QString, bool, MsgId, int)),
	    this, SLOT(watchMessageInserted(QString, bool, MsgId, int)));
	dbSet->disconnect(SIGNAL(messageDataDeleted(QString, bool, MsgId)),
	    this, SLOT(watchMessageDataDeleted(QString, bool, MsgId)));

	/* Close database. */
	delete dbSet;

	return true;
}

void DbContainer::watchMadeAvailable(const QString &primaryKey, bool testing)
{
	emit madeAvailable(AcntId(primaryKey, testing));
}

void DbContainer::watchOpened(const QString &primaryKey, bool testing)
{
	emit opened(AcntId(primaryKey, testing));
}

void DbContainer::watchChangedLocallyRead(const QString &primaryKey,
    bool testing, const QList<MsgId> &msgIds, bool read)
{
	emit changedLocallyRead(AcntId(primaryKey, testing), msgIds, read);
}

void DbContainer::watchChangedProcessState(const QString &primaryKey,
    bool testing, const QList<MsgId> &msgIds,
    enum MessageDb::MessageProcessState state)
{
	emit changedProcessState(AcntId(primaryKey, testing), msgIds, state);
}

void DbContainer::watchMessageInserted(const QString &primaryKey, bool testing,
    const MsgId &msgId, int direction)
{
	emit messageInserted(AcntId(primaryKey, testing), msgId, direction);
}

void DbContainer::watchMessageDataDeleted(const QString &primaryKey,
    bool testing, const MsgId &msgId)
{
	emit messageDataDeleted(AcntId(primaryKey, testing), msgId);
}

const QString DbContainer::dbDriverType("QSQLITE");
