#include "piintrospector.h"
#include "pifile.h"
#include "pitime.h"
#include "pidir.h"
#include <QClipboard>


QPIIntrospector::QPIIntrospector(QWidget * parent): QMainWindow(parent), peer("__introspection_client__") {
	setupUi(this);
#if QT_VERSION >= 0x050000
	tree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
	tree->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
	CONNECTU(&peer, dataReceivedEvent, this, peerReceived)
	startTimer(100);
}


void QPIIntrospector::changeEvent(QEvent * e) {
	QMainWindow::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange:
		retranslateUi(this);
		break;
	default:
		break;
	}
}


void QPIIntrospector::timerEvent(QTimerEvent * ) {
	listApp->blockSignals(true);
	QString cs = listApp->currentItem() ? listApp->currentItem()->text() : "";
	listApp->clear();
	peer.lock();
	piForeachC (PIPeer::PeerInfo & p, peer.allPeers()) {
		QString pn = PI2QString(p.name);
		listApp->addItem(pn);
		if (pn == cs)
			listApp->setCurrentRow(listApp->count() - 1);
	}
	peer.unlock();
	listApp->blockSignals(false);
}


void QPIIntrospector::buildTree(QByteArray d) {
	PIVector<PIIntrospectionThreads::ThreadInfo> threads;
	PIByteArray pd = Q2PIByteArray(d);
	pd >> threads;
	tree->clear();
	piForeachC (PIIntrospectionThreads::ThreadInfo & t, threads) {
		QTreeWidgetItem * ti = new QTreeWidgetItem();
		ti->setText(0, QString(PI2QString(t.name) + " (%1)").arg(t.id));
		tree->addTopLevelItem(ti);
	}
}


void QPIIntrospector::buildDumpSection(QTreeWidgetItem * pi, PIString & str) {
}


void QPIIntrospector::on_listApp_currentRowChanged(int r) {
	if (r < 0) cur_server.clear();
	else cur_server = Q2PIString(listApp->item(r)->text());
}


void QPIIntrospector::peerReceived(const PIString & from, const PIByteArray & data) {
	if (from != cur_server) return;
	PIString appname;
	PIIntrospectionContainers cont;
	PIByteArray ba(data);
	ba >> appname >> cont;// >> threads.threads;
	QMetaObject::invokeMethod(labelAppname, "setText", Qt::QueuedConnection, Q_ARG(QString, PI2QString(appname)));
	QMetaObject::invokeMethod(labelCount, "setText", Qt::QueuedConnection, Q_ARG(QString, QString::number(cont.count)));
	QMetaObject::invokeMethod(labelAlloc, "setText", Qt::QueuedConnection, Q_ARG(QString, PI2QString(PIString::readableSize(cont.bytes_allocated))));
	QMetaObject::invokeMethod(labelUsed, "setText", Qt::QueuedConnection, Q_ARG(QString, PI2QString(PIString::readableSize(cont.bytes_used))));
	QMetaObject::invokeMethod(this, "buildTree", Qt::QueuedConnection, Q_ARG(QByteArray, PI2QByteArray(ba)));
	//piCout << appname;
}
