/* VisualColorStyleChooser.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 "VisualColorStyleChooser.h"
#include "Components/Visualization/VisualStyleTypes.h"
#include "Database/Connector.h"
#include "Database/VisualStyles.h"

#include "Utils/Mutex.h"
#include "Utils/Algorithm.h"

namespace
{
	std::mutex mtx; // NOLINT(*-avoid-non-const-global-variables)
}

struct VisualColorStyleChooser::Private
{
	QList<RawColorStyle> styles;
};

VisualColorStyleChooser::VisualColorStyleChooser() :
	m {Pimpl::make<Private>()}
{
	reload();
}

VisualColorStyleChooser::~VisualColorStyleChooser() noexcept = default;

RawColorStyle VisualColorStyleChooser::style(int i) const
{
	i = std::max(i, 0);
	i = std::min(m->styles.size() - 1, i);

	return m->styles[i];
}

int VisualColorStyleChooser::count() const { return m->styles.size(); }

void VisualColorStyleChooser::reload()
{
	LOCK_GUARD(mtx) // NOLINT(*-const-correctness)

	auto* db = DB::Connector::instance()->visualStyleConnector();

	m->styles = db->getRawColorStyles();

	if(m->styles.isEmpty())
	{
		const auto rgbStyle = Util::createRgbStyle();
		const auto bwStyle = Util::createBwStyle();

		db->insertRawColorStyle(rgbStyle);
		db->insertRawColorStyle(bwStyle);

		m->styles << rgbStyle << bwStyle;
	}
}
