#include "pivariant_edit_enum.h"

#include "piqt.h"


PIValueTreeEditEnum::PIValueTreeEditEnum(QWidget * parent): QDialog(parent) {
	Q_INIT_RESOURCE(qad_piqt_widgets);
	setupUi(this);
}


PIValueTreeEditEnum::~PIValueTreeEditEnum() {}


bool PIValueTreeEditEnum::showFor(const PIVariantTypes::Enum & v) {
	ret = PIVariantTypes::Enum();

	treeWidget->clear();
	for (auto e: v.enum_list)
		addItem(PI2QString(e.name), e.value);

	if (exec() != QDialog::Accepted) return false;

	for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) {
		auto * ti = treeWidget->topLevelItem(i);
		ret << PIVariantTypes::Enumerator(ti->text(1).toInt(), Q2PIString(ti->text(0)));
	}

	return true;
}


QTreeWidgetItem * PIValueTreeEditEnum::addItem(QString n, int v) {
	auto * ti = new QTreeWidgetItem({n, QString::number(v)});
	treeWidget->addTopLevelItem(ti);
	auto f = ti->flags();
	f.setFlag(Qt::ItemIsEditable);
	ti->setFlags(f);
	return ti;
}


void PIValueTreeEditEnum::on_buttonAdd_clicked() {
	bool is_edit = false;
	for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) {
		auto * ti = treeWidget->topLevelItem(i);
		for (int c = 0; c < treeWidget->columnCount(); ++c) {
			if (treeWidget->isPersistentEditorOpen(ti, c)) {
				is_edit = true;
				break;
			}
		}
		if (is_edit) break;
	}
	if (is_edit) {
		buttonAdd->setFocus();
		treeWidget->setFocus();
	}
	int max = -1;
	for (int i = 0; i < treeWidget->topLevelItemCount(); ++i)
		max = piMaxi(max, treeWidget->topLevelItem(i)->text(1).toInt());

	auto * ti = addItem("name", max + 1);
	treeWidget->editItem(ti, 0);
}


void PIValueTreeEditEnum::on_buttonRemove_clicked() {
	qDeleteAll(treeWidget->selectedItems());
}


void PIValueTreeEditEnum::on_buttonClear_clicked() {
	treeWidget->clear();
}
