#include "animone/util/osx.h"

#include <memory>
#include <string>

#include <libproc.h>
#include <sys/sysctl.h>

namespace animone::internal::osx::util {

static bool GetProcessNameFromProcPidPath(pid_t pid, std::string& result) {
	result.assign(PROC_PIDPATHINFO_MAXSIZE, '\0');

	int ret = proc_pidpath(pid, result.data(), result.size() * sizeof(char));
	if (ret <= 0)
		return false;

	/* find the last slash, if there's none, we're done here */
	size_t last_slash = result.rfind('/');
	if (last_slash == std::string::npos)
		return true;

	result.erase(0, last_slash + 1);
	return true;
}

static bool GetProcessNameFromProcName(pid_t pid, std::string& result) {
	result.assign(2 * MAXCOMLEN, '\0');

	int size = proc_name(pid, &result.front(), result.length());

	/* if size is MAXCOMLEN or 2 * MAXCOMLEN, assume
	 * this method won't work and our result is truncated */
	if (size <= 0 || size == MAXCOMLEN || size == 2 * MAXCOMLEN)
		return false;

	result.resize(size);
	return true;
}

bool GetProcessName(pid_t pid, std::string& result) {
	if (GetProcessNameFromProcName(pid, result))
		return true;

	if (GetProcessNameFromProcPidPath(pid, result))
		return true;

	return false;
}

} // namespace animone::internal::osx::util
