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

#include "src/datovka_shared/compat/compiler.h" /* macroStdMove */
#include "src/datovka_shared/json/basic.h" /* Json::Int64StringList */
#include "src/datovka_shared/json/draft_interface.h"
#include "src/datovka_shared/utility/date_time.h"
#include "src/models/draft_model.h"
#include "src/models/helper.h"

DraftTableModel::DraftTableModel(QObject *parent)
    : QAbstractTableModel(parent),
    m_entries()
{
}

int DraftTableModel::rowCount(const QModelIndex &parent) const
{
	if (parent.isValid()) {
		return 0;
	} else {
		return m_entries.size();
	}
}

int DraftTableModel::columnCount(const QModelIndex &parent) const
{
	if (parent.isValid()) {
		return 0;
	} else {
		return MAX_COLNUM;
	}
}


QVariant DraftTableModel::data(const QModelIndex &index, int role) const
{
	const int row = index.row();
	const int col = index.column();
	if (Q_UNLIKELY((row < 0) || (row >= rowCount()))) {
		Q_ASSERT(0);
		return QVariant();
	}
	if (Q_UNLIKELY((col < 0) || (col >= columnCount()))) {
		Q_ASSERT(0);
		return QVariant();
	}

	switch (role) {
	case Qt::DisplayRole:
		switch (col) {
		case COL_DRAFT_ID:
			return m_entries.at(row).id;
			break;
		case COL_ACNT_ID:
			return m_entries.at(row).acntId.username();
			break;
		case COL_CREAT_TIME:
			{
				const QDateTime &time =
				    m_entries.at(row).creationTime;
				return time.isValid() ?
				    time.toString(Utility::dateTimeDisplayFormat) :
				    QString();
			}
			break;
		case COL_MOD_TIME:
			{
				const QDateTime &time =
				    m_entries.at(row).modificationTime;
				return time.isValid() ?
				    time.toString(Utility::dateTimeDisplayFormat) :
				    QString();
			}
			break;
		case COL_ANNOTATION:
			return m_entries.at(row).dmDraft.dmEnvelope().dmAnnotation();
			break;
		case COL_RECIPIENTS:
			return m_entries.at(row).dmDraft.dmRecipients().join(", ");
			break;
		default:
			Q_ASSERT(0);
			return QVariant();
			break;
		}
		break;

	case Qt::AccessibleTextRole:
		switch (col) {
		case COL_DRAFT_ID:
		case COL_ACNT_ID:
		case COL_CREAT_TIME:
		case COL_MOD_TIME:
		case COL_ANNOTATION:
		case COL_RECIPIENTS:
			{
				QString dataStr(data(index).toString());
				if (Q_UNLIKELY(dataStr.isEmpty())) {
					dataStr = tr("unspecified");
				}
				return headerData(col, Qt::Horizontal).toString() +
				    QStringLiteral(" ") + dataStr;
			}
			break;
		default:
			return QVariant();
			break;
		}
		break;

	case ROLE_PROXYSORT:
		switch (col) {
		case COL_DRAFT_ID:
			return m_entries.at(row).id;
			break;
		case COL_ACNT_ID:
			return ModelHelper::sortRank(
			    m_entries.at(row).acntId.strId(),
			    m_entries.at(row).id);
			break;
		case COL_CREAT_TIME:
			return ModelHelper::sortRank(
			    m_entries.at(row).creationTime,
			    m_entries.at(row).id);
			break;
		case COL_MOD_TIME:
			return ModelHelper::sortRank(
			    m_entries.at(row).modificationTime,
			    m_entries.at(row).id);
			break;
		case COL_ANNOTATION:
			return ModelHelper::sortRank(
			    m_entries.at(row).dmDraft.dmEnvelope().dmAnnotation(),
			    m_entries.at(row).id);
			break;
		case COL_RECIPIENTS:
			return ModelHelper::sortRank(
			    data(index, Qt::DisplayRole).toString(),
			    m_entries.at(row).id);
			break;
		default:
			return QVariant();
			break;
		}
		break;

	default:
		return QVariant();
		break;
	}
}

Qt::ItemFlags DraftTableModel::flags(const QModelIndex &index) const
{
	Qt::ItemFlags defaultFlags = QAbstractTableModel::flags(index);
	return defaultFlags;
}

QVariant DraftTableModel::headerData(int section, Qt::Orientation orientation,
    int role) const
{
	Q_UNUSED(orientation);

	switch (role) {
	case Qt::DisplayRole:
		switch (section) {
		case COL_DRAFT_ID:
			return tr("Identifier");
			break;
		case COL_ACNT_ID:
			return tr("Data Box");
			break;
		case COL_CREAT_TIME:
			return tr("Created");
			break;
		case COL_MOD_TIME:
			return tr("Modified");
			break;
		case COL_ANNOTATION:
			return tr("Subject");
			break;
		case COL_RECIPIENTS:
			return tr("Recipients");
			break;
		default:
			Q_ASSERT(0);
			return QVariant();
			break;
		}
		break;

	default:
		return QVariant();
		break;
	}
}

void DraftTableModel::appendData(const QList<DraftEntry> &entryList)
{
	if (Q_UNLIKELY(entryList.isEmpty())) {
		return;
	}

	beginInsertRows(QModelIndex(), rowCount(),
	    rowCount() + entryList.size() - 1);

	m_entries.append(entryList);

	endInsertRows();
}

#ifdef Q_COMPILER_RVALUE_REFS
void DraftTableModel::appendData(QList<DraftEntry> &&entryList)
{
	if (Q_UNLIKELY(entryList.isEmpty())) {
		return;
	}

	beginInsertRows(QModelIndex(), rowCount(),
	    rowCount() + entryList.size() - 1);

	m_entries.append(::std::move(entryList));

	endInsertRows();
}
#endif /* Q_COMPILER_RVALUE_REFS */

void DraftTableModel::updateOrAppendData(const QList<DraftEntry> &entryList)
{
	if (Q_UNLIKELY(entryList.isEmpty())) {
		return;
	}

	QList<DraftEntry> appendedEntries;
	for (const DraftEntry &entry : entryList) {
		int row = findRow(entry.id);
		if (row >= 0) {
			m_entries[row] = entry;
			Q_EMIT dataChanged(index(row, COL_ACNT_ID), index(row, COL_RECIPIENTS));
		} else {
			appendedEntries.append(entry);
		}
	}

	if (!appendedEntries.isEmpty()) {
		appendData(macroStdMove(appendedEntries));
	}
}

DraftEntry DraftTableModel::entryAt(int row) const
{
	if (Q_UNLIKELY((row < 0) || (row >= rowCount()))) {
		Q_ASSERT(0);
		return DraftEntry();
	}

	return m_entries.at(row);
}

bool DraftTableModel::entryForId(qint64 draftId, DraftEntry &entry) const
{
	int row = findRow(draftId);
	if (row >= 0) {
		entry = m_entries.at(row);
		return true;
	} else {
		entry = DraftEntry();
		return false;
	}
}

void DraftTableModel::removeAllRows(void)
{
	if (!m_entries.isEmpty()) {
		beginResetModel();
		m_entries.clear();

		endResetModel();
	}
}

void DraftTableModel::remove(const Json::Int64StringList &ids)
{
	QList<int> rowsDescending;

	/* Collect unique rows in descending order. */
	{
		QSet<int> rowSet;

		for (const qint64 &draftId : ids) {
			int row = findRow(draftId);
			if (row >= 0) {
				rowSet.insert(row);
			}
		}

#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
		rowsDescending = QList<int>(rowSet.constBegin(), rowSet.constEnd());
#else /* < Qt-5.14.0 */
		rowsDescending = rowSet.toList();
#endif /* >= Qt-5.14.0 */

		::std::sort(rowsDescending.begin(), rowsDescending.end(), ::std::greater<int>());
	}

	for (int foundRow : rowsDescending) {
		beginRemoveRows(QModelIndex(), foundRow, foundRow);

		m_entries.removeAt(foundRow);

		endRemoveRows();
	}
}

int DraftTableModel::findRow(qint64 draftId) const
{
	int foundRow = -1;
	for (int row = 0; row < rowCount(); ++row) {
		if (m_entries.at(row).id == draftId) {
			foundRow = row;
			break;
		}
	}
	return foundRow;
}
