// Copyright (c) 2026 - 2026 kio@little-bat.de
// BSD-2-Clause license
// https://opensource.org/licenses/BSD-2-Clause

#include "FrameBufferImageItem.h"
#include <QQuickWindow>
#include <QSGSimpleTextureNode>


FrameBufferImageItem::FrameBufferImageItem(QQuickItem* parent) : QQuickItem(parent)
{
	// Crucial: flag that this item has visual content to render
	setFlag(ItemHasContents, true);
}

void FrameBufferImageItem::setImage(const QImage& image)
{
	if (m_image == image) return;
	m_image		   = image;
	m_imageChanged = true;
	emit imageChanged();
	update(); // Schedules a redraw on the Scene Graph thread
}

QSGNode* FrameBufferImageItem::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData*)
{
	auto* node = static_cast<QSGSimpleTextureNode*>(oldNode);

	if (m_image.isNull())
	{
		delete node;
		return nullptr;
	}

	if (!node) { node = new QSGSimpleTextureNode(); }

	// Only recreate/update the texture if the image actually changed
	if (m_imageChanged)
	{
		// Create an OpenGL/Vulkan/Metal hardware texture from the QImage
		QSGTexture* texture = window()->createTextureFromImage(m_image, QQuickWindow::TextureIsOpaque);

		// Out with the old texture, in with the new
		delete node->texture();
		node->setTexture(texture);
		node->setOwnsTexture(true);
		m_imageChanged = false;
	}

	// Stretch the texture to fill the QML Item's boundaries
	node->setRect(boundingRect());
	return node;
}
