#include "piqt_iodevice_edit.h"

#include "piqt_iodevice_edit_dialog.h"
#include "qvariantedit_custom.h"

#include <QBoxLayout>
#include <QLineEdit>
#include <QToolButton>
#include <piiodevice.h>
#include <piqt.h>


IODeviceEdit::IODeviceEdit(QWidget * parent): QWidget(parent) {
	dlg  = new IODeviceEditDialog();
	line = new QLineEdit();
	btn  = new QToolButton();
	setLayout(new QBoxLayout(QBoxLayout::LeftToRight));
	layout()->setContentsMargins(0, 0, 0, 0);
	layout()->addWidget(line);
	layout()->addWidget(btn);
	connect(btn, SIGNAL(clicked(bool)), this, SLOT(buttonDlg_clicked()));
	line->setReadOnly(true);
	btn->setText(QString());
	btn->setIcon(QIcon(":/icons/configure.png"));
	btn->setToolTip(tr("Edit ..."));
}


IODeviceEdit::~IODeviceEdit() {
	delete dlg;
}


QVariant IODeviceEdit::value() const {
	return QVariant::fromValue(dev);
}


bool IODeviceEdit::isReadOnly() const {
	return btn->isHidden();
}


void IODeviceEdit::setDevice(const QAD::IODevice & d) {
	if (dev.toString() == d.toString()) return;
	dev = d;
	line->setText(dev.toString());
	line->setCursorPosition(0);
	emit valueChanged();
}


void IODeviceEdit::setValue(const QVariant & v) {
	setDevice(v.value<QAD::IODevice>());
}


void IODeviceEdit::setReadOnly(bool yes) {
	btn->setHidden(yes);
}


void IODeviceEdit::buttonDlg_clicked() {
	QAD::IODevice d = dlg->getIODevice(dev);
	if (!d.isValid()) return;
	setDevice(d);
}


class Factory: public QVariantEditorFactoryBase {
public:
	Factory() {}
	virtual QWidget * createEditor() { return new IODeviceEdit(); }
};


__IODeviceEditRegistrator__::__IODeviceEditRegistrator__() {
	QVariantEditorFactories::registerEditorFactory(qMetaTypeId<QAD::IODevice>(), new Factory());
	__QADTypesRegistrator__::instance()->toString_funcs.insert(qMetaTypeId<QAD::IODevice>(), &QAD_IODevice_toString);
}


void QAD_IODevice_toString(const QVariant & v, QString & r) {
	PIVariantTypes::IODevice sd = Q2PIVariant(v).toIODevice();
	//	piCout << sd;
	PIIODevice * rd             = PIIODevice::createFromVariant(sd);
	if (rd) {
		PIString ps = rd->constructFullPath();
		r           = PI2QString(ps);
	} else {
		piCout << "error in " << sd;
	}
}
