/*
Copyright (C) 2006 Evan Teran
                   eteran@alum.rit.edu

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "DialogAttach.h"
#include "Types.h"

#include <QMap>
#include <QHeaderView>
#include <QDir>
#include <QTextStream>

#ifdef Q_OS_FREEBSD
#include <kvm.h>
#endif

struct ProcessInfo {
	edb::pid_t	pid;
	edb::uid_t	uid;
	QString		name;
};

//------------------------------------------------------------------------------
// Name: DialogAttach(QWidget *parent) : QDialog(parent)
// Desc: constructor
//------------------------------------------------------------------------------
DialogAttach::DialogAttach(QWidget *parent) : QDialog(parent) {
	ui.setupUi(this);
	ui.tableWidget->verticalHeader()->hide();
	ui.tableWidget->horizontalHeader()->setStretchLastSection(true);
}

//------------------------------------------------------------------------------
// Name: isNumeric(const QString &s)
// Desc: returns true if the string only contains decimal digits
//------------------------------------------------------------------------------
bool DialogAttach::isNumeric(const QString &s) {
	bool ret = false;
	foreach(QChar ch, s) {
		ret = ch.isDigit();
		if(!ret) {
			break;
		}
	}

	return ret;
}

//------------------------------------------------------------------------------
// Name: on_txtSearch_textChanged(const QString &text)
// Desc: 
//------------------------------------------------------------------------------
void DialogAttach::on_txtSearch_textChanged(const QString &text) {
	updateList(text);
}

//------------------------------------------------------------------------------
// Name: updateList(const QString &filter)
// Desc: 
//------------------------------------------------------------------------------
void DialogAttach::updateList(const QString &filter) {

	QMap<edb::pid_t, ProcessInfo> procs;
#if defined(Q_OS_LINUX)

	QDir procDir("/proc/");
	QFileInfoList entries = procDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
	
	foreach(QFileInfo info, entries) {
		if(isNumeric(info.fileName())) {

			const QDir proc(info.absoluteFilePath());		
			const QString status = proc.absolutePath() + "/stat";
			
			ProcessInfo procInfo;
			procInfo.pid = info.fileName().toUInt();
			procInfo.uid = info.ownerId();
			
			QFile file(status);
	        if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
				QTextStream in(&file);

				int pid;
				QString name;
				// we already know the pid, so this'll just get read and ignored
				in >> pid;
				// get the name
				in >> name;
				// chop off the silly ( and )
				procInfo.name = name.mid(1);
				procInfo.name.chop(1);

			}
			procs.insert(procInfo.pid, procInfo);
		}
	}

	const edb::uid_t myUID = getuid();
#elif defined(Q_OS_FREEBSD)
	
	char ebuffer[_POSIX2_LINE_MAX];
	int numprocs;
	const edb::uid_t myUID = getuid();
	kvm_t *const kaccess = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, 0, O_RDONLY, ebuffer);
	if(kaccess != 0) {
		struct kinfo_proc *const kprocaccess = kvm_getprocs(kaccess, KERN_PROC_ALL, (int)myUID, &numprocs);
		if(kprocaccess != 0) {
			for(int i = 0; i < numprocs; ++i) {
				ProcessInfo procInfo;
				procInfo.pid = kprocaccess[i]->ki_pid;
				procInfo.uid = kprocaccess[i]->ki_uid;
				procInfo.name = kprocaccess[i]->ki_comm;
				procs.insert(procInfo.pid, procInfo);
			}
		}
	}
	
#else
	#error "Unsupported Platform"
#endif
	const bool filterUID = ui.chkFilterUID->isChecked();
	const QString lowerFilter = filter.toLower();
	ui.tableWidget->setSortingEnabled(false);
	ui.tableWidget->setRowCount(0);

	foreach(ProcessInfo procInfo, procs) {

		const QString procName = procInfo.name;
		
		if(filter.isEmpty() || procName.toLower().contains(lowerFilter)) {	
			if(!filterUID || procInfo.uid == myUID) {
				const int row = ui.tableWidget->rowCount();
				ui.tableWidget->insertRow(row);
				
				QTableWidgetItem *const itemPID = new QTableWidgetItem;
				itemPID->setData(Qt::DisplayRole, procInfo.pid);
				
				QTableWidgetItem *const itemUID = new QTableWidgetItem;
				itemUID->setData(Qt::DisplayRole, procInfo.uid);
				
				ui.tableWidget->setItem(row, 0, itemPID);
				ui.tableWidget->setItem(row, 1, itemUID);
		        ui.tableWidget->setItem(row, 2, new QTableWidgetItem(procInfo.name));
			}
		}
	}
	ui.tableWidget->setSortingEnabled(true);
}

//------------------------------------------------------------------------------
// Name: showEvent(QShowEvent *event)
// Desc: 
//------------------------------------------------------------------------------
void DialogAttach::showEvent(QShowEvent *event) {
	Q_UNUSED(event);
	updateList(ui.txtSearch->text());
}

//------------------------------------------------------------------------------
// Name: on_chkFilterUID_clicked(bool checked)
// Desc: 
//------------------------------------------------------------------------------
void DialogAttach::on_chkFilterUID_clicked(bool checked) {
	Q_UNUSED(checked);
	updateList(ui.txtSearch->text());
}
