#include "QDetailsView.h"
#include <QVBoxLayout>
#include <QQmlComponent>
#include <QQmlEngine>
#include <QQuickItem>
#include <QUrl>
#include "QQuickDetailsViewMananger.h"

QDetailsView::QDetailsView(QWidget* parent)
	: QWidget(parent)
	, mQuickWidget(nullptr)
	, mQuickDetailsView(nullptr)
{
	setMinimumSize(200, 200);

	if (!QQuickDetailsViewManager::Get()->isInitialized()) {
		QQuickDetailsViewManager::Get()->initialize();
	}

	mQuickWidget = new QQuickWidget(this);
	mQuickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);

	const QString qmlContent = R"(
        import QtQuick 
		import QtQuick.Controls
        import QtQuick.DetailsView 


        DetailsView {
			id: detailsView 
            anchors.fill: parent
			boundsBehavior: Flickable.OvershootBounds
			ScrollBar.vertical: ScrollBar {
				parent: detailsView.parent
				width : 10
				anchors.top: detailsView.top
				anchors.right: detailsView.right
				anchors.bottom: detailsView.bottom
			}
        }
    )";

	QQmlComponent component(mQuickWidget->engine());
	component.setData(qmlContent.toUtf8(), QUrl(""));
	QObject* rootObject = component.create();
	if (!component.errors().isEmpty()) {
		qDebug() << component.errorString();
	}
	if (rootObject) {
		mQuickWidget->setSource(QUrl());
		mQuickWidget->engine()->setObjectOwnership(rootObject, QQmlEngine::CppOwnership);

		QQuickItem* rootItem = qobject_cast<QQuickItem*>(rootObject);
		if (rootItem) {
			mQuickWidget->setContent(QUrl(), &component, rootItem);
			mQuickDetailsView = qobject_cast<QQuickDetailsView*>(rootItem);
		}
	}

	QVBoxLayout* layout = new QVBoxLayout(this);
	layout->setContentsMargins(0, 0, 0, 0);
	layout->addWidget(mQuickWidget);
	setLayout(layout);
}

QQuickDetailsView* QDetailsView::getQuickDetailsView() const
{
	return mQuickDetailsView;
}

void QDetailsView::setObject(QObject* inObject)
{
	QQuickItem* rootObject = mQuickWidget->rootObject();
	if (rootObject) {
		rootObject->setProperty("Object", QVariant::fromValue(inObject));
	}
}

QObject* QDetailsView::getObject() const
{
	QQuickItem* rootObject = mQuickWidget->rootObject();
	if (rootObject) {
		return rootObject->property("Object").value<QObject*>();
	}
	return nullptr;
}
