/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2014  Georg Rudoy
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **********************************************************************/

#include "collectiondelegate.h"
#include <QPainter>
#include <QApplication>
#include "localcollectionmodel.h"

namespace LeechCraft
{
namespace LMP
{
	const int IconSize = 32;
	const int Padding = 2;

	CollectionDelegate::CollectionDelegate (QObject *parent)
	: QStyledItemDelegate (parent)
	, DefaultAlbum_ (QIcon::fromTheme ("media-optical").pixmap (64, 64))
	, PXCache_ (100000)
	{
	}

	void CollectionDelegate::paint (QPainter *painter,
			const QStyleOptionViewItem& optionOld, const QModelIndex& index) const
	{
		const int type = index.data (LocalCollectionModel::Role::Node).toInt ();

		QStyleOptionViewItemV4 option = optionOld;

		auto& pal = option.palette;
		if (!(option.features & QStyleOptionViewItemV4::Alternate))
		{
			QLinearGradient grad (0, 0, option.rect.width (), 0);
			grad.setColorAt (0, pal.color (QPalette::Window).darker (105));
			grad.setColorAt (0.5, pal.color (QPalette::Window).darker (120));
			grad.setColorAt (1, pal.color (QPalette::Window).darker (105));
			option.backgroundBrush = QBrush (grad);
		}

		if (type != LocalCollectionModel::NodeType::Album)
			PaintOther (painter, option, index);
		else
			PaintAlbum (painter, option, index);
	}

	QSize CollectionDelegate::sizeHint (const QStyleOptionViewItem& option, const QModelIndex& index) const
	{
		QSize result = QStyledItemDelegate::sizeHint (option, index);
		if (index.data (LocalCollectionModel::Role::Node).toInt () == LocalCollectionModel::NodeType::Album)
			result.setHeight (std::max (result.height (), IconSize));
		return result;
	}

	void CollectionDelegate::PaintBorder (QPainter *painter, QStyleOptionViewItemV4 option) const
	{
		auto& pal = option.palette;
		QLinearGradient grad (0, 0, option.rect.width (), 0);
		grad.setColorAt (0, pal.color (QPalette::Button));
		grad.setColorAt (0.5, pal.color (QPalette::Dark));
		grad.setColorAt (1, pal.color (QPalette::Button));

		painter->setPen ({ grad, 1 });
		painter->drawLine (option.rect.bottomLeft (), option.rect.bottomRight ());
	}

	void CollectionDelegate::PaintWPixmap (QPainter *painter,
			QStyleOptionViewItemV4 option, const QModelIndex& index, const QPixmap& px) const
	{
		QStyle *style = option.widget ?
				option.widget->style () :
				QApplication::style ();

		painter->save ();

		style->drawPrimitive (QStyle::PE_PanelItemViewItem, &option, painter, option.widget);

		const int maxIconHeight = option.rect.height () - Padding * 2;
		const bool hasIcon = !px.isNull ();
		if (hasIcon)
		{
			const auto horShift = (maxIconHeight - px.size ().width ()) / 2;
			const auto vertShift = (option.rect.height () - px.size ().height ()) / 2;
			painter->drawPixmap (option.rect.left () + horShift,
					option.rect.top () + vertShift,
					px);
		}

		const auto& text = index.data ().toString ();
		if (option.state & QStyle::State_Selected)
			painter->setPen (option.palette.color (QPalette::HighlightedText));
		painter->setFont (option.font);
		painter->drawText (option.rect.adjusted (hasIcon ? maxIconHeight + 2 * Padding : 0, 0, 0, 0),
				Qt::AlignVCenter, text);

		PaintBorder (painter, option);

		painter->restore ();
	}

	void CollectionDelegate::PaintOther (QPainter *painter,
			QStyleOptionViewItemV4 option, const QModelIndex& index) const
	{
		const int maxIconHeight = option.rect.height () - Padding * 2;
		const auto& icon = index.data (Qt::DecorationRole).value<QIcon> ();
		PaintWPixmap (painter, option, index,
				icon.pixmap ({ maxIconHeight, maxIconHeight }));
	}

	void CollectionDelegate::PaintAlbum (QPainter *painter,
			QStyleOptionViewItemV4 option, const QModelIndex& index) const
	{
		const QString& path = index.data (LocalCollectionModel::Role::AlbumArt).value<QString> ();
		QPixmap *cached = PXCache_ [path];
		QPixmap px = cached ? *cached : QPixmap (path);
		const bool special = !px.isNull ();
		if (!special)
			px = DefaultAlbum_;

		const int maxIconHeight = option.rect.height () - Padding * 2;
		px = px.scaled (maxIconHeight, maxIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
		if (!cached && special)
			PXCache_.insert (path, new QPixmap (px), px.size ().width () * px.size ().height ());

		PaintWPixmap (painter, option, index, px);
	}
}
}
