#include <QMessageBox>
#include <QInputDialog>
#include "device_streams_dialog.h"
#include "piqt.h"

const char name_property[] = "__name__";


DeviceStreamsDialog::DeviceStreamsDialog(QWidget * parent): QDialog(parent), Ui::DeviceStreamsDialog() {
	setupUi(this);
	buttonAdd->setMenu(&add_menu);
}


DeviceStreamsDialog::~DeviceStreamsDialog() {
}


void DeviceStreamsDialog::setDeviceStreams(const QVector<SHS::DeviceParameters> & dsl) {
	tree->clear();
	for (const auto & d: dsl) {
		auto * dev = RUNTIME->connection.deviceByName(Q2PIString(d.name));
		tree->addTopLevelItem(new QTreeWidgetItem(QStringList() << d.name << PI2QString(dev ? dev->path() : "") << QString::number(d.send_time_grid_period_ms)));
	}
}


QVector<SHS::DeviceParameters> DeviceStreamsDialog::deviceStreams() const {
	QVector<SHS::DeviceParameters> ret;
	for (int i = 0; i < tree->topLevelItemCount(); ++i) {
		SHS::DeviceParameters p;
		auto * ti = tree->topLevelItem(i);
		p.name = ti->text(0);
		p.send_time_grid = true;
		p.send_time_grid_period_ms = ti->text(2).toDouble();
		ret << p;
	}
	return ret;
}


int DeviceStreamsDialog::exec() {
	createAddMenu();
	return QDialog::exec();
}


void DeviceStreamsDialog::createAddMenu() {
	qDeleteAll(add_menu.actions());
	auto * a = new QAction(tr("No devices"));
	a->setEnabled(false);
	add_menu.addAction(a);
	auto dl = RUNTIME->connection.boundedDevices();
	for (auto * d: dl) {
		QString dn = PI2QString(RUNTIME->connection.deviceNames(d)[0]);
		QString dp = PI2QString(d->path());
		a = new QAction(tr("%1 (%2)").arg(dn, dp));
		a->setProperty(name_property, dn);
		add_menu.addAction(a);
		connect(a, &QAction::triggered, this, [this,dn,dp](){
			tree->addTopLevelItem(new QTreeWidgetItem(QStringList() << dn << dp << "20"));
			checkAddMenu();
		});
	}
	checkAddMenu();
}


void DeviceStreamsDialog::checkAddMenu() {
	auto al = add_menu.actions();
	if (al.isEmpty()) return;
	QStringList exists;
	for (int i = 0; i < tree->topLevelItemCount(); ++i)
		exists << tree->topLevelItem(i)->text(0);
	bool empty = true;
	for (int i = 1; i < al.size(); ++i) {
		bool vis = !exists.contains(al[i]->property(name_property).toString());
		al[i]->setVisible(vis);
		if (vis) empty = false;
	}
	al[0]->setVisible(empty);
}


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


void DeviceStreamsDialog::on_tree_itemClicked(QTreeWidgetItem * item, int column) {
	if (!item) return;
	auto f = item->flags();
	f.setFlag(Qt::ItemIsEditable, column == 2);
	item->setFlags(f);
}
