/* PlaylistDBWrapper.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 "PlaylistDBWrapper.h"

#include "Utils/FileUtils.h"
#include "Utils/MetaData/MetaDataList.h"
#include "Utils/Playlist/CustomPlaylist.h"
#include "Utils/Tagging/TagReader.h"

#include "Database/Connector.h"
#include "Database/Playlist.h"

#include <utility>

namespace
{
	MetaDataList applyTags(MetaDataList tracks, const Tagging::TagReaderPtr& tagReader)
	{
		// TODO: replace by views
		for(auto& track: tracks)
		{
			if(track.id() < 0)
			{
				if(const auto maybeTrack = tagReader->readMetadata(track.filepath()); maybeTrack.has_value())
				{
					track = maybeTrack.value();
				}
			}
		}

		return tracks;
	}

	QList<CustomPlaylist> applyTagsToPlaylists(QList<CustomPlaylist> playlists, const Tagging::TagReaderPtr& tagReader)
	{
		for(auto& playlist: playlists)
		{
			auto tracks = playlist.tracks();
			auto changedTracks = applyTags(std::move(tracks), tagReader);
			playlist.setTracks(std::move(changedTracks));
		}

		return playlists;
	}

	DB::Playlist* db() { return DB::Connector::instance()->playlistConnector(); }
}

namespace Playlist
{
	QList<CustomPlaylist> loadPlaylists(const StoreType type, const SortOrder sortOrder, const bool getTracks, const Tagging::TagReaderPtr& tagReader)
	{
		auto playlists = db()->getAllPlaylists(type, getTracks, sortOrder);
		return getTracks
		       ? applyTagsToPlaylists(std::move(playlists), tagReader)
		       : playlists;
	}

	QList<CustomPlaylist> loadPlaylistsByIds(const QList<Id>& ids, const bool getTracks, const Tagging::TagReaderPtr& tagReader)
	{
		auto* playlistConnector = DB::Connector::instance()->playlistConnector();
		auto result = QList<CustomPlaylist> {};
		for(const auto& id: ids)
		{
			auto playlist = playlistConnector->getPlaylistById(id, getTracks);
			if(playlist.id() >= 0)
			{
				result << playlist;
			}
		}

		return applyTagsToPlaylists(std::move(result), tagReader);
	}
}