#include "cmdhelper.h"
#include <stdio.h> 
#include <QProcess>

#define BUFFER_LENGTH 100
cmdHelper::cmdHelper(QObject* parent) : QObject(parent)
{

}

QString cmdHelper::getLinuxVersion()
{
	std::string str;
	if (cmdHelper::Instance()->exec("cat /proc/version", str))
	{
		QString qstr = QString::fromStdString(str);
		return qstr.section(')', 0, 0).append(")");
	}
	return QString("Unable to get Linux version!");
}

QString cmdHelper::getDCMTKVersion()
{
	std::string str;
	if (cmdHelper::Instance()->exec2("zypper info dcmtk", str))
	{
		QString qstr = QString::fromStdString(str);
		QStringList strList = qstr.split('\n');
		for (int i = 0; i < strList.size(); i++)
		{
			if (strList.at(i).contains("Version"))
			{
				QStringList strList2 = strList.at(i).split(':');
				return QString("DCMTK %1").arg(strList2[1]);
			}
		}
	};
	return QString("Unable to get DCMTK version!");
}
bool cmdHelper::getDiskSize(double& size)
{
	std::string str;
	if (cmdHelper::Instance()->exec2("df /home/usct/data -h", str))
	{
		QString qstr = QString::fromStdString(str);
		QStringList strList = qstr.split('\n');
		strList[1].replace(QRegExp("[\\s]+"), " ");
		QStringList strList2 = strList[1].split(" ");
		int pos = strList2[1].lastIndexOf(QChar('G'));

		size = strList2[1].left(pos).toDouble();

		return true;
	};
	return false;
}

bool cmdHelper::getDiskUsed(double& used)
{
	std::string str;
	if (cmdHelper::Instance()->exec2("df /home/usct/data -h", str))
	{
		QString qstr = QString::fromStdString(str);
		QStringList strList = qstr.split('\n');
		if (strList.length()<3) return false;
		strList[1].replace(QRegExp("[\\s]+"), " ");
		QStringList strList2 = strList[1].split(" ");
		int pos = strList2[2].lastIndexOf(QChar('G'));

		used = strList2[2].left(pos).toDouble();

		return true;
	};
	return false;
}

bool cmdHelper::exec(const char* cmd, std::string& result) {
#ifndef WIN32
	FILE* fp = nullptr;
	if (!(fp = popen(cmd, "r")))
	{
		result.append(strerror(errno));
		pclose(fp);
		return false;
	}
	char buffer[BUFFER_LENGTH];
	memset(buffer, 0, BUFFER_LENGTH);
	while (fgets(buffer, BUFFER_LENGTH, fp))
	{
		result.append(buffer, strlen(buffer) - 1);
	}
	pclose(fp);
	return true;
#else
	return false;
#endif // WIN32

}

bool cmdHelper::exec2(const char* cmd, std::string& result)
{

	QProcess* myProcess = new QProcess;
	QStringList args;
	args << "-c" << cmd;
	connect(myProcess, SIGNAL(finished(int)), myProcess, SLOT(deleteLater()));
	myProcess->start("/bin/sh", args);

	if (!myProcess->waitForFinished() || myProcess->exitCode() != 0) {
		return false;
	}

	result.append(myProcess->readAllStandardOutput());
	return true;

}
