/*
 * 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 <algorithm> /* ::std::sort, ::std::upper_bound */
#include <QPainter>
#include <QPainterPath>

#include "src/datovka_shared/json/basic.h"
#include "src/datovka_shared/localisation/localisation.h"
#include "src/datovka_shared/log/log.h"
#include "src/delegates/tag_item.h"
#include "src/dimensions/dimensions.h"

TagItem::TagItem(void)
    : Json::TagEntry()
{
}

TagItem::TagItem(const Json::TagEntry &entry)
    : Json::TagEntry(entry)
{
}

int TagItem::paint(QPainter *painter, const QStyleOptionViewItem &option) const
{
	if (Q_UNLIKELY(Q_NULLPTR == painter)) {
		Q_ASSERT(0);
		return 0;
	}

	const QRect &rect(option.rect);

	painter->save();

	const QSize hint(sizeHint(option));
	int border = (rect.height() - hint.height()) / 2;

	int width = hint.width();
	int height = hint.height();

	QRectF drawnRect(0, border, width, height);

	QPainterPath path;
	int rounding = (int)(0.15 * height);
	path.addRoundedRect(drawnRect, rounding, rounding, Qt::AbsoluteSize);

	if (option.state & QStyle::State_Selected) {
		painter->fillRect(rect, option.palette.highlight());
	}

	painter->setRenderHint(QPainter::Antialiasing, true);
	painter->translate(rect.x(), rect.y());

	const int margin = Dimensions::margin(option);

	painter->translate(margin, 0);

	QColor rectColour("#" + colour());
	if (Q_UNLIKELY(!rectColour.isValid())) {
		logWarningNL("Invalid tag colour '%s'. Using 'ffffff'",
		    colour().toUtf8().constData());
		rectColour = QColor("#ffffff"); /* Should be valid now. */
		Q_ASSERT(rectColour.isValid());
	}

	QPen pen(rectColour, 1);
	painter->setPen(pen);
	painter->fillPath(path, rectColour);
	painter->drawPath(path);

	/* TODO -- Obtain foreground colour. */
	painter->setPen(
	    QPen(adjustForegroundColour(Qt::black, rectColour), 1));
	painter->drawText(drawnRect, Qt::AlignCenter, name());

	painter->restore();

	return width + margin;
}

QSize TagItem::sizeHint(const QStyleOptionViewItem &option) const
{
	const QFont &font(option.font);

	int height = QFontMetrics(font).height();
	const int padding = Dimensions::padding(height);

	/*
	 * Stopped using deprecated QFontMetrics::width().
	 * https://kdepepo.wordpress.com/2019/08/05/about-deprecation-of-qfontmetricswidth/
	 * https://doc.qt.io/qt-5/qfontmetrics-obsolete.html#width
	 */
	int width = QFontMetrics(font).boundingRect(name()).width();
	width += 2 * padding;

	height += 2 * padding;

	return QSize(width, height);
}

QColor TagItem::adjustForegroundColour(const QColor &fgColour,
    const QColor &tagColour)
{
	Q_UNUSED(fgColour);

	int r = tagColour.red();
	int g = tagColour.green();
	int b = tagColour.blue();

#if 0
	int colour = (r << 16) + (g << 8) + b;
	return (colour > (0xffffff / 2)) ? Qt::black : Qt::white;
#else
	int yiq = ((299 * r) + (587 * g) + (114 * b)) / 1000;
	return (yiq >= 128) ? Qt::black : Qt::white;
#endif
}

TagItemList::TagItemList(void)
    : QList<TagItem>()
{
}

TagItemList::TagItemList(const Json::TagEntryList &tagList)
    : QList<TagItem>()
{
	for (const Json::TagEntry &entry : tagList) {
		QList<TagItem>::append(TagItem(entry));
	}
}

TagItemList::TagItemList(const QList<TagItem> &tagList)
    : QList<TagItem>(tagList)
{
}

void TagItemList::paint(QPainter *painter,
    const QStyleOptionViewItem &option) const
{
	if (Q_UNLIKELY(Q_NULLPTR == painter)) {
		Q_ASSERT(0);
		return;
	}

	painter->save();

	for (const TagItem &tag : *this) {
		int width = tag.paint(painter, option);
		painter->translate(width, 0);
	}

	painter->restore();
}

QSize TagItemList::sizeHint(const QStyleOptionViewItem &option) const
{
	int width = 0;
	const int margin = Dimensions::margin(option);

	for (const TagItem &tag : *this) {
		width += tag.sizeHint(option).width();
		width += 2 * margin;
	}
	width += margin;

	/* Don't care about vertical dimensions here. */
	return QSize(width, 1);
}

bool TagItemList::updateTag(const Json::TagEntry &entry)
{
	int pos = indexOfId(entry.id());
	if (pos < 0) {
		return false;
	}

	this->operator[](pos) = TagItem(entry);
	return true;
}

bool TagItemList::deleteTags(const Json::Int64StringList &ids)
{
	if (this->isEmpty()) {
		return false;
	}

	bool removed = false;

	for (qint64 id : ids) {
		int pos = indexOfId(id);
		if (pos < 0) {
			continue;
		}

		this->removeAt(pos);
		removed = true;
		if (this->isEmpty()) {
			break;
		}
	}

	return removed;
}

/*!
 * @brief Used for sorting tag lists.
 *
 * @param[in] a First tag item.
 * @param[in] b Second tag item.
 * @return True if \a a comes before \a b.
 */
static
bool tagItemLessName(const TagItem &a, const TagItem &b)
{
	return Localisation::stringCollator.compare(a.name(), b.name()) < 0;
}

void TagItemList::sortNames(void)
{
	::std::sort(this->begin(), this->end(), tagItemLessName);
}

TagItemList::iterator TagItemList::upperBoundName(const TagItem &item)
{
	return ::std::upper_bound(this->begin(), this->end(), item, tagItemLessName);
}

int TagItemList::indexOfId(qint64 tagId) const
{
	for (int i = 0; i < this->size(); ++i) {
		if (this->at(i).id() == tagId) {
			return i;
		}
	}

	return -1;
}

bool TagItemList::containsId(qint64 tagId) const
{
	/*
	 * Cannot use ::std::lower_bound here because the list is not sorted
	 * according to identifiers.
	 */
	for (const TagItem &item : *this) {
		if (item.id() == tagId) {
			return true;
		}
	}

	return false;
}
