#include "propertystorage_editor.h"

#include "propertystorage.h"
#include "qvariantedit.h"

#include <QGridLayout>
#include <QToolButton>


PropertyStorageEditor::PropertyStorageEditor(QWidget * parent): QWidget(parent) {
	setLayout(new QGridLayout());
	layout()->setContentsMargins(0, 0, 0, 0);
	storage = nullptr;
}


PropertyStorageEditor::~PropertyStorageEditor() {
	clear();
}


void PropertyStorageEditor::clear() {
	qDeleteAll(_widgets);
	_widgets.clear();
}


bool PropertyStorageEditor::isEmpty() const {
	return static_cast<QGridLayout *>(layout())->count() == 0;
}


void PropertyStorageEditor::setStorage(PropertyStorage * s) {
	clear();
	storage = s;
	if (!storage) return;
	int r            = 0;
	auto layoutProps = static_cast<QGridLayout *>(layout());
	for (const PropertyStorage::Property & p: *storage) {
		auto lbl = new QLabel(p.name);
		_widgets << lbl;
		lbl->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
		layoutProps->addWidget(lbl, r, 0);
		auto ve = new QVariantEdit();
		ve->setValue(p.value);
		ve->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
		ve->setMinimumWidth(50);
		connect(ve, SIGNAL(valueChanged(QVariant)), this, SIGNAL(changed()));
		layoutProps->addWidget(ve, r, 1);
		_widgets << ve;
		lbl = new QLabel(p.comment);
		lbl->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
		layoutProps->addWidget(lbl, r, 2);
		_widgets << lbl;
		++r;
	}
}


void PropertyStorageEditor::applyProperties() {
	if (!storage) return;
	QList<PropertyStorage::Property> & props(storage->properties());
	auto layoutProps = static_cast<QGridLayout *>(layout());
	for (int r = 0; r < layoutProps->rowCount(); ++r) {
		if (layoutProps->itemAtPosition(r, 0) == nullptr || layoutProps->itemAtPosition(r, 1) == nullptr) {
			continue;
		}
		QLabel * lbl      = qobject_cast<QLabel *>(layoutProps->itemAtPosition(r, 0)->widget());
		QVariantEdit * ve = qobject_cast<QVariantEdit *>(layoutProps->itemAtPosition(r, 1)->widget());
		if (lbl == nullptr || ve == nullptr) {
			continue;
		}
		QString pn = lbl->text();
		for (int i = 0; i < props.size(); ++i) {
			PropertyStorage::Property & p(props[i]);
			if (p.name == pn) {
				p.value = ve->value();
				break;
			}
		}
	}
}
