#include "properties_actions.h"
#include <QGridLayout>
#include <QPushButton>


PropertiesActions::PropertiesActions(QWidget * parent): QWidget(parent) {
	setLayout(new QGridLayout());
	layout()->setContentsMargins(0, 0, 0, 0);
}


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


void PropertiesActions::clear() {
	qDeleteAll(_widgets);
	_widgets.clear();
	actions_.clear();
}


bool PropertiesActions::isEmpty() const {
	return ((QBoxLayout*)layout())->count() == 0;
}


void PropertiesActions::setActions(const QList<SHPluginBase::PluginAction> & al) {
	clear();
	actions_ = al;
	QGridLayout * layoutActions = (QGridLayout*)layout();
	for (int i = 0; i < al.size(); ++i) {
		const SHPluginBase::PluginAction & a(al[i]);
		QIcon icon;
		switch (a.iconType) {
			case SHPluginBase::EditIcon     : icon = QIcon(":/icons/document-edit.png"); break;
			case SHPluginBase::ConfigureIcon: icon = QIcon(":/icons/configure.png"); break;
			case SHPluginBase::RunIcon      : icon = QIcon(":/icons/quickopen.png"); break;
			case SHPluginBase::BurnIcon     : icon = QIcon(":/icons/run-build-install-root.png"); break;
			case SHPluginBase::CustomIcon   : icon = a.icon; break;
			default: break;
		}
		QPushButton * pb = new QPushButton(icon, a.caption);
		pb->setProperty("action_name", a.name);
		pb->setToolTip(a.tooltip);
		connect(pb, SIGNAL(clicked()), this, SLOT(pluginAction_triggered()));
		_widgets << pb;
		layoutActions->addWidget(pb, i / 2, i % 2);
	}
}


void PropertiesActions::check() {
	QMap<QString, QWidget * > aw;
	foreach (QWidget * w, _widgets)
		aw[w->property("action_name").toString()] = w;
	foreach (const SHPluginBase::PluginAction & a, actions_) {
		QWidget * w = aw.value(a.name);
		if (!w) continue;
		bool en = true;
		checkRequest(a, &en);
		w->setEnabled(en);
	}
}


void PropertiesActions::pluginAction_triggered() {
	if (!sender()) return;
	QString aname = sender()->property("action_name").toString();
	if (aname.isEmpty()) return;
	foreach (const SHPluginBase::PluginAction & a, actions_)
		if (a.name == aname) {
			emit executeAction(a);
			return;
		}
}
