#include <QScrollBar>
#include <QGroupBox>
#include <QBoxLayout>
#include "pins_user_editor.h"
#include "blockitem.h"
#include "blockbusitem.h"
#include "ui_pins_user_editor.h"


PinsUserEditor::PinsUserEditor(QWidget * parent): QWidget(parent) {
	ui = new Ui::PinsUserEditor();
	ui->setupUi(this);
	block_ = 0;
	bus_ = 0;
}


PinsUserEditor::~PinsUserEditor() {
}


void PinsUserEditor::clear() {
	qDeleteAll(_widgets);
	_widgets.clear();
	block_ = 0;
	bus_ = 0;
}


bool PinsUserEditor::isEmpty() const {
	return _widgets.isEmpty();
}


void PinsUserEditor::setBlock(BlockItem * b) {
	clear();
	block_ = b;
	if (!block_) return;
	foreach (BlockItemPin * p, block_->pins()) {
		PropertiesUserEditor * ped = new PropertiesUserEditor();
		ped->setStorage(p);
		if (ped->isEmpty()) {
			delete ped;
			continue;
		}
		ped->setProperty("__pin__", qulonglong(p));
		connect(ped, SIGNAL(resetStorageRequest(PropertyStorage*)), this, SLOT(properties_resetStorageRequest(PropertyStorage*)));
		QGroupBox * gb = new QGroupBox(p->text());
		gb->setLayout(new QBoxLayout(QBoxLayout::BottomToTop));
		gb->layout()->addWidget(ped);
		ui->layoutPins->addWidget(gb);
		_widgets << gb;
	}
	setMinimumWidth(ui->layoutPins->sizeHint().width());
}


void PinsUserEditor::setBus(BlockBusItem * b) {
	clear();
	bus_ = b;
	if (!bus_) return;
	foreach (BlockItemPin * p, bus_->connectedPins()) {
		PropertiesUserEditor * ped = new PropertiesUserEditor();
		ped->setStorage(p);
		if (ped->isEmpty()) {
			delete ped;
			continue;
		}
		ped->setProperty("__pin__", qulonglong(p));
		connect(ped, SIGNAL(resetStorageRequest(PropertyStorage*)), this, SLOT(properties_resetStorageRequest(PropertyStorage*)));
		QGroupBox * gb = new QGroupBox(p->parent()->propertyValueByName("name").toString() + ": " + p->text());
		gb->setLayout(new QBoxLayout(QBoxLayout::BottomToTop));
		gb->layout()->addWidget(ped);
		ui->layoutPins->addWidget(gb);
		_widgets << gb;
	}
	setMinimumWidth(ui->layoutPins->sizeHint().width());
}


void PinsUserEditor::applyProperties() {
	QList<PropertiesUserEditor*> peds = findChildren<PropertiesUserEditor*>();
	foreach (PropertiesUserEditor * p, peds)
		p->applyProperties();
}


void PinsUserEditor::properties_resetStorageRequest(PropertyStorage * s) {
	if (!sender()) return;
	BlockItemPin * pin = (BlockItemPin*)(sender()->property("__pin__").toULongLong());
	if (!pin) return;
	s->properties() = pin->properties();
}


