#include "bus_properties.h"
#include "pins_user_editor.h"
#include <QLabel>
#include <QPushButton>
#include <QToolButton>
#include <QProcess>


BusProperties::BusProperties(QWidget * parent): QDialog(parent), Ui::BusProperties() {
	setupUi(this);
	connect(properties, SIGNAL(changed()), actions_, SLOT(check()));
	bus = 0;
}


BusProperties::~BusProperties() {
}


QDialog::DialogCode BusProperties::show(BlockBusItem * b) {
	bus = b;
	if (bus == 0) return QDialog::Rejected;
	load();
	return (QDialog::DialogCode)exec();
}


void BusProperties::save() {
	if (bus == 0) return;
	properties->applyProperties();
	QList<PinsUserEditor*> puds = findChildren<PinsUserEditor*>();
	foreach (PinsUserEditor * p, puds)
		p->applyProperties();
	actions_->check();
}


void BusProperties::load() {
	if (bus == 0) return;
	groupProps->hide();
	groupActions->hide();
	groupBlockPins->hide();
	BusType bt = SHCORE->databaseStorage().srcBus(bus);
	labelID->setNum(bt.id);
	labelName->setText(bt.name);
	labelDescription->setText(bt.description);
	qDeleteAll(_widgets);
	_widgets.clear();
	
	properties->setStorage(bus);
	groupProps->setVisible(!properties->isEmpty());
	
	SHPluginBaseBus * shp = SHCORE->busPlugin(bus);
	if (shp)
		actions_->setActions(shp->addActions(bus));
	groupActions->setVisible(!actions_->isEmpty());

	PinsUserEditor * pue = new PinsUserEditor();
	pue->setBus(bus);
	if (!pue->isEmpty()) {
		layoutBlockPins->addWidget(pue);
		_widgets << pue;
	} else {
		delete pue;
	}
	groupBlockPins->setVisible(layoutBlockPins->count() > 0);
	actions_->check();
}


void BusProperties::accept() {
	save();
	bus = 0;
	QDialog::accept();
}


void BusProperties::reject() {
	bus = 0;
	QDialog::reject();
}


void BusProperties::on_buttonBox_clicked(QAbstractButton * button) {
	if (buttonBox->buttonRole(button) == QDialogButtonBox::ResetRole)
		load();
	if (buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole)
		save();
}


void BusProperties::on_buttonRecreate_clicked() {
	if (!bus) return;
	bus->properties() = SHCORE->databaseStorage().srcBus(bus).properties.properties();
	load();
}


void BusProperties::on_buttonEditDB_clicked() {
	if (!bus) return;
	save();
	emit editDatabaseBus(SHCORE->databaseStorage().srcBus(bus).id);
	accept();
}


void BusProperties::on_properties_resetStorageRequest(PropertyStorage * s) {
	*s = SHCORE->databaseStorage().srcBus(bus).properties;
}


void BusProperties::on_actions__executeAction(SHPluginBase::PluginAction action) {
	if (!bus) return;
	if (action.flags.testFlag(SHPluginBase::ApplyProperties))
		save();
	SHCORE->pluginBusAction(bus, action);
	if (action.flags.testFlag(SHPluginBase::UpdateProperties))
		load();
	if (action.flags.testFlag(SHPluginBase::CloseDialog))
		done(QDialog::Accepted);
}


void BusProperties::on_actions__checkRequest(SHPluginBase::PluginAction action, bool * ret) {
	if (!bus) return;
	SHPluginBaseBus * p = SHCORE->busPlugin(bus);
	if (!p) return;
	*ret = p->checkAction(bus, action);
}
