/* CastosPodcastParser.cpp, (Created on 28.05.2024) */

/* Copyright (C) 2011-2024 Michael Lugmair
 *
 * 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 "CastosPodcastParser.h"
#include "Utils/Logger/Logger.h"

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

namespace
{
	RadioStation objectToRadioStation(const QJsonObject& obj, const int index)
	{
		const auto title = obj["title"].toString();
		const auto shortDescription = obj["description"].toString().trimmed();
		const auto coverUrl = obj["image"].toString();
		const auto url = obj["url"].toString();
		const auto radioUrl = RadioUrl {0, url, {}, {}};

		return {index, title, {}, {}, {}, shortDescription, shortDescription, coverUrl, url, {radioUrl}};
	}

	QList<RadioStation> parseRadioStations(const QJsonDocument& doc)
	{
		auto result = QList<RadioStation> {};

		const auto items = doc["data"].toArray();
		auto i = 0;
		for(const auto& item: items)
		{
			result << objectToRadioStation(item.toObject(), i);
			i++;
		}

		return result;
	}
}

CastosPodcastParser::~CastosPodcastParser() = default;

QList<RadioStation> CastosPodcastParser::parse(const QByteArray& data) const
{
	auto error = QJsonParseError {};
	auto jsonDocument = QJsonDocument::fromJson(data, &error);
	if(error.error != QJsonParseError::NoError)
	{
		spLog(Log::Warning, this) << error.errorString();
		return {};
	}

	const auto success = jsonDocument["success"].toBool();
	if(!success)
	{
		spLog(Log::Warning, this) << "Cannot parse podcast: " << jsonDocument["data"].toString();
		return {};
	}

	return parseRadioStations(jsonDocument);
}

