#include "CFileManager.hpp"

void CFileManager::open(const char mode) {
	DEBUG_LOG(trace, "Kernel", "FileManager", "file " + m_filePath + " opened.")

	switch (mode) {
	case 'r':
		m_filePtr = fopen(m_filePath.c_str(), "r");
		break;
	case 'w':
		m_filePtr = fopen(m_filePath.c_str(), "w");
		break;
	default:
		throw std::invalid_argument("\'mode\' parameter must be \'r\' (read) or \'w\' (write)");
	}
	if (m_filePtr == NULL) {
		throw CFileException("File \"" + m_filePath + "\" can't be opened");
	}
}

void CFileManager::close(void) {
	DEBUG_LOG(trace, "Kernel", "FileManager", "file " + m_filePath + " closed.")

	if (m_filePtr != NULL) {
		fclose(m_filePtr);
	}
}

CFileManager::CFileManager(std::string path) :
	m_filePath(path),
	m_filePtr(NULL) {
}

CFileManager::~CFileManager(void) {
}

std::string CFileManager::getPath(void) const {
	return m_filePath;
}

void CFileManager::write(std::string content) {
	open('w');

	fputs(content.c_str(), m_filePtr);

	close();
}

std::string CFileManager::read(void) {
	open('r');

	std::string out("");
	char ch;

	while ((ch = fgetc(m_filePtr)) != EOF) {
		out += ch;
	}

	close();

	return out;
}