#include "pidumper.h"
#include "pifile.h"
#include "pitime.h"
#include "pidir.h"
//#include "ccm.h"
#include <QClipboard>
#ifdef CC_GCC
#  include <unistd.h>
#endif

PIDumper::PIDumper(QWidget * parent): QMainWindow(parent) {
	setupUi(this);
#if QT_VERSION >= 0x050000
	treeDump->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
	treeDump->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
}


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


void PIDumper::buildDump() {
	treeDump->clear();
	if (!dump.contains('{')) return;
	PIString app = dump.takeWord();
	if (app != "application") return;
	dump.takeLine();
	QTreeWidgetItem * ti;
	while (!dump.isEmpty()) {
		PIString line = dump.takeLine();
		if (line.contains('{')) {
			ti = new QTreeWidgetItem();
			dump.prepend(line + "\n");
			buildDumpSection(ti, dump);
			treeDump->addTopLevelItem(ti);
			continue;
		}
		int colon = line.find(":");
		if (colon < 0) continue;
		PIString name = line.takeLeft(colon).trim();
		PIString value = line.cutLeft(1).trim();
		if (value.startsWith("\"")) value.cutLeft(1);
		if (value.endsWith("\"")) value.cutRight(1);
		ti = new QTreeWidgetItem(QStringList() << PI2QString(name) << PI2QString(value));
		treeDump->addTopLevelItem(ti);
	}
	on_checkDumpHideService_toggled(checkDumpHideService->isChecked());
}


void PIDumper::buildDumpSection(QTreeWidgetItem * pi, PIString & str) {
	PIString section = str.takeLeft(str.find("{")).trim();
	PIString value;
	if (section.contains('(')) {
		value = section;
		section = value.takeLeft(value.find('('));
		value = value.takeRange("(", ")");
	}
	pi->setText(0, piqt(section));
	pi->setText(1, piqt(value));
	//if (section == "PIObjects")
	PIString range = str.takeRange("{", "}");
	QTreeWidgetItem * ti;
	PIString fs;
	if (section == "PIObjects" || section == "properties") fs = ":";
	if (section == "methodsEH") fs = " ";
	if (section == "connections") fs = "->";
	while (!range.isEmpty()) {
		PIString line = range.takeLine().trim();
		if (line.contains('{')) {
			ti = new QTreeWidgetItem(pi);
			range.prepend(line + "\n");
			buildDumpSection(ti, range);
			//treeDump->addTopLevelItem(ti);
			continue;
		}
		if (line.left(line.find(":")).trim() == "count") {
			pi->setText(1, "[" + PI2QString(line.right(line.length() - line.find(":") - 1).trim()) + "]");
			continue;
		}
		int colon = line.find(fs);
		if (colon < 0) continue;
		PIString name = line.takeLeft(colon).trim();
		PIString value = line.cutLeft(fs.size_s()).trim();
		if (value.startsWith("\"")) value.cutLeft(1);
		if (value.endsWith("\"")) value.cutRight(1);
		if (name.endsWith(":")) name.cutRight(1);
		if (name.isEmpty() && value.isEmpty()) continue;
		ti = new QTreeWidgetItem(pi, QStringList() << PI2QString(name) << PI2QString(value));
		//treeDump->addTopLevelItem(ti);
	}
}


void PIDumper::on_buttonDumpMake_clicked() {
	if (radioDumpCurrent->isChecked()) {
		PICout::setBufferActive(true, true);
		dumpApplication();
		dump = PICout::buffer();
		PICout::setBufferActive(false);
	} else {
		int pid = lineDumpCustom->text().toInt();
		if (pid == 0) return;
		if (system(QString("kill -USR1 %1").arg(pid).toLatin1().constData()) < 0) return;
		PIString dp = PIDir::home().path() + "/_PIP_DUMP_" + PIString::fromNumber(pid);
		PITimeMeasurer tm;
		while (tm.elapsed_s() < 5. && !PIFile::isExists(dp)) {
			piMSleep(10);
		}
		//piSleep(2.);
		PIFile f(dp, PIIODevice::ReadOnly);
		if (!f.isOpened()) return;
		dump = PIString(f.readAll());
		f.remove();
	}
	buildDump();
}


void PIDumper::on_buttonDumpClipboard_clicked() {
	dump = Q2PIString(QApplication::clipboard()->text());
	buildDump();
}


void PIDumper::on_checkDumpHideService_toggled(bool on) {
	QList<QTreeWidgetItem * > il = treeDump->findItems("", Qt::MatchContains | Qt::MatchRecursive);
	foreach (QTreeWidgetItem * i, il) {
		if (on) {
			if (i->text(0).startsWith("class"))
				i->setHidden(i->text(1).contains("__S__"));
		} else
			i->setHidden(false);
	}
}
