#include "user_roles_dialog.h"


UserRolesDialog::UserRolesDialog(QWidget * parent): QDialog(parent), Ui::UserRolesDialog() {
	setupUi(this);
}


UserRolesDialog::~UserRolesDialog() {
}


QVector<SHS::UserRole> UserRolesDialog::getRoles() const {
	QVector<SHS::UserRole> ret;
	SHS::UserRole r;
	for (int i = 0; i < tree->topLevelItemCount(); ++i) {
		auto * ti = tree->topLevelItem(i);
		r.name = ti->text(0);
		r.display_name = ti->text(1);
		r.password = ti->text(2);
		r.privilege = ti->text(3).toInt();
		ret << r;
	}
	return ret;
}


bool UserRolesDialog::exec(const QVector<SHS::UserRole> & roles) {
	tree->clear();
	for (auto r: roles)
		addRole(r);
	return QDialog::exec() == QDialog::Accepted;
}


QTreeWidgetItem * UserRolesDialog::addRole(const SHS::UserRole & r) {
	auto * ti = new QTreeWidgetItem({r.name, r.display_name, r.password, QString::number(r.privilege)});
	ti->setFlags(ti->flags() | Qt::ItemIsEditable);
	tree->addTopLevelItem(ti);
	return ti;
}


void UserRolesDialog::on_buttonAdd_clicked() {
	SHS::UserRole r;
	r.name = "name";
	r.password = "1234";
	r.privilege = 1;
	tree->editItem(addRole(r));
}


void UserRolesDialog::on_buttonRemove_clicked() {
	qDeleteAll(tree->selectedItems());
}
