/* CoverViewPixmapCache.cpp */

/* Copyright (C) 2011-2024 Michael Lugmair (Lucio Carreras)
 *
 * This file is part of sayonara player
 *
 * 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/>.
 */

#include "CoverViewPixmapCache.h"
#include "Components/Covers/CoverLocation.h"

#include "Utils/Image.h"
#include "Utils/Set.h"

#include <QCache>
#include <QString>
#include <QPixmap>
#include <QPixmapCache>

using Library::CoverViewPixmapCache;

namespace
{
	constexpr const auto ImageSize = 250;
	constexpr const auto CacheLimit = 125'000;
}

struct CoverViewPixmapCache::Private
{
	QPixmapCache pixmaps;
	Util::Set<Hash> validHashes;
	QPixmap invalidCover;

	Private() :
		invalidCover {Cover::Location::invalidPath()}
	{
		pixmaps.setCacheLimit(CacheLimit);
	}
};

CoverViewPixmapCache::CoverViewPixmapCache() :
	m{Pimpl::make<Private>()} {}

CoverViewPixmapCache::~CoverViewPixmapCache() = default;

QPixmap CoverViewPixmapCache::invalidPixmap() const
{
	return m->invalidCover;
}

void CoverViewPixmapCache::addPixmap(const Hash& hash, const QPixmap& pixmap)
{
	if(!pixmap.isNull())
	{
		m->validHashes.insert(hash);
		m->pixmaps.insert(hash, pixmap.scaled({ImageSize, ImageSize}, Qt::KeepAspectRatio, Qt::SmoothTransformation));
	}
}

bool CoverViewPixmapCache::pixmap(const Hash& hash, QPixmap& pixmap) const
{
	return m->pixmaps.find(hash, &pixmap);
}

bool CoverViewPixmapCache::isOutdated(const Hash& hash) const
{
	return not m->validHashes.contains(hash);
}

void CoverViewPixmapCache::setAllOutdated()
{
	m->validHashes.clear();
}

void CoverViewPixmapCache::clear()
{
	m->pixmaps.clear();
}
