/* platform.cpp */

#ifdef _WIN32
#include <Windows.h>
#endif

#include "platform.h"

std::string file_get_contents(char* path) {
	FILE* f_in = NULL;
	if (!strcmp(path, "-")) {
		f_in = stdin;
	} else {
		fopen_s(&f_in, path, "rb");
		if (!f_in) {
			fprintf(stderr, "Couldn't open file \"%s\" for reading\n", path);
			exit(1);
		}
	}

	// read content
	char f_tmp[2048] = { 0 };
	size_t f_len = 0;
	std::string content;
	while (f_len = fread_s(f_tmp, 2048, 1, 2048, f_in)) {
		content.append(f_tmp, f_len);
	}

	if (f_in != stdin) {
		fclose(f_in);
	}

	return content;
}

static std::string dirname_from_path__inner(std::string path, char path_separator) {
	auto rpos = path.find_last_of(path_separator);
	if (rpos == path.npos) {
		return "."; // unknown
	} else {
		return path.substr(0, rpos);
	}
}

std::string dirname_from_path(std::string path) {
	std::string ret = dirname_from_path__inner(path, '/');

#ifdef _WIN32
	if (ret == ".") {
		ret = dirname_from_path__inner(path, '\\');
	}
#endif

	return ret;
}

void set_working_directory(const char* path) {
#ifdef _WIN32
	SetCurrentDirectory(path);
#else
	chdir(path);
#endif
}

std::string get_working_directory() {
	char buff[512] = { 0 };
#ifdef _WIN32
	GetCurrentDirectory(sizeof(buff), buff);
#else
	getcwd(buff, sizeof(buff));
#endif

	return buff;
}