/*
 * 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 "src/datovka_shared/localisation/localisation.h"
#include "src/datovka_shared/records_management/models/upload_hierarchy_proxy_model.h"

RecMgmt::UploadHierarchyProxyModel::UploadHierarchyProxyModel(QObject *parent)
    : QSortFilterProxyModel(parent)
{
}

/*
 * There's a problem in Qt-5 because QSortFilterProxyModel::setFilterFixedString()
 * sets the QRegExp but not the QRegularExpression.
 * QRegularExpression::escape() is only available since Qt-5.15 and
 * QSortFilterProxyModel::setFilterRegularExpression() is available since Qt-5.12.
 */
#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
#  define _filterRegularExpressionEmpty() filterRegularExpression().pattern().isEmpty()
#  define _filterRegularExpression() filterRegularExpression()
#else /* < Qt-5.15 */
#  define _filterRegularExpressionEmpty() filterRegExp().isEmpty()
#  define _filterRegularExpression() filterRegExp()
#endif /* >= Qt-5.15 */

bool RecMgmt::UploadHierarchyProxyModel::filterAcceptsRow(int sourceRow,
    const QModelIndex &sourceParent) const
{
	/*
	 * Adapted from
	 * qtbase/src/corelib/itemmodels/qsortfilterproxymodel.cpp .
	 */

	if (_filterRegularExpressionEmpty()) {
		return true;
	}

	QModelIndex sourceIndex(sourceModel()->index(sourceRow,
	    filterKeyColumn(), sourceParent));
	return filterAcceptsItem(sourceIndex);
}

bool RecMgmt::UploadHierarchyProxyModel::lessThan(const QModelIndex &sourceLeft,
    const QModelIndex &sourceRight) const
{
	QVariant leftData(sourceModel()->data(sourceLeft, sortRole()));
	QVariant rightData(sourceModel()->data(sourceRight, sortRole()));

	if (Q_LIKELY(leftData.canConvert<QString>())) {
		Q_ASSERT(rightData.canConvert<QString>());
		return Localisation::stringCollator.compare(leftData.toString(),
		    rightData.toString()) < 0;
	} else {
		return QSortFilterProxyModel::lessThan(sourceLeft, sourceRight);
	}
}

bool RecMgmt::UploadHierarchyProxyModel::filterAcceptsItem(
    const QModelIndex &sourceIdx) const
{
	if (!sourceIdx.isValid()) {
		return false;
	}

	/*
	 * Qt-6 has changed the definition of QStringList
	 * https://www.qt.io/blog/qlist-changes-in-qt-6
	 * As a result.
	 *
	 * Qt-5:
	 *   QVariant(QString("test")).canConvert<QString>() == true
	 *   QVariant(QString("test")).toString() == "test"
	 *   QVariant(QString("test")).canConvert<QStringList>() == true
	 *   QVariant(QString("test")).toStringList().join("|") == "test"
	 *   QVariant(QStringList{"test01", "test02"}).canConvert<QString>() == false
	 *   QVariant(QStringList{"test01", "test02"}).toString() == ""
	 *   QVariant(QStringList{"test01", "test02"}).canConvert<QStringList>() == true
	 *   QVariant(QStringList{"test01", "test02"}).toStringList().join("|") == "test01|test02"
	 *
	 * Qt-6:
	 *   QVariant(QString("test")).canConvert<QString>() == true
	 *   QVariant(QString("test")).toString() == "test"
	 *   QVariant(QString("test")).canConvert<QStringList>() == true
	 *   QVariant(QString("test")).toStringList().join("|") == "test"
	 *   QVariant(QStringList{"test01", "test02"}).canConvert<QString>() == true // !
	 *   QVariant(QStringList{"test01", "test02"}).toString() == "" // !
	 *   QVariant(QStringList{"test01", "test02"}).canConvert<QStringList>() == true
	 *   QVariant(QStringList{"test01", "test02"}).toStringList().join("|") == "test01|test02"
	 */

	QStringList filterData;
	{
		const QVariant data(
		    sourceModel()->data(sourceIdx, filterRole()));
		if (data.canConvert<QStringList>()) {
			filterData += data.toStringList();
		} else if (data.canConvert<QString>()) {
			/*
			 * This should be covered by the conversion
			 * to QStringList but let's keep it here for now.
			 */
			filterData += data.toString();
		} else {
			return false;
		}
	}

	foreach (const QString &str, filterData) {
		if (str.contains(_filterRegularExpression())) {
			return true;
		}
	}
	return false;
}
