#include "itemloadersource.h"

#include <QJsonArray>

ItemLoaderSource::ItemLoaderSource(const QJsonObject& json, QObject *parent):
	ItemSource{parent},
	json(json)
{
}

void ItemLoaderSource::refresh()
{
	std::vector<ItemAddRequest> itemAddRequests;
	const QJsonArray itemsArray(json["Items"].toArray());
	for(int i = 0; i < itemsArray.size(); ++i)
	{
		if(!itemsArray[i].isObject())
			continue;

		const QJsonObject itemObject = itemsArray[i].toObject();
		std::shared_ptr<Item> newItem = Item::loadItem(itemObject);
		if(newItem)
		{
			qDebug()<<"Loaded item"<<newItem->getName();
			ItemAddRequest request;
			request.type = ITEM_UPDATE_LOADED;
			request.payload = newItem;
			request.changes = ItemFieldChanges(true);
			if(newItem->hasActors())
				request.changes.actors = true;
			request.changes.value = false;
			itemAddRequests.push_back(request);
		}
	}
	gotItems(itemAddRequests);
}

void ItemLoaderSource::updateJson(const QJsonObject& json)
{
	this->json = json;
}

ItemLoaderSource::~ItemLoaderSource()
{}

