
#include <Spectre/System/Log/FileWriter.h>

namespace sp { namespace log {

FileWriter::FileWriter(const std::string file) :
m_fd	(NULL)
{
	if (file.length() > 0) {
		open(file);
	}
}

FileWriter::~FileWriter()
{
	if (m_fd) {
		close();
	}
}

bool FileWriter::open(const std::string file)
{
	if (!close()) {
		return false;
	}

	if (file == "stderr") {
		m_fd = stderr;
		return true;
	}

	if (file == "stdout") {
		m_fd = stdout;
		return true;
	}

	m_fd = fopen(file.c_str(), "a");
	if (m_fd == NULL) {
		return false;
	}

	return true;
}

bool FileWriter::close()
{
	if (m_fd) {
		// stdout and stderr can not be closed.
		if (m_fd == stdout || m_fd == stderr) {
			m_fd = NULL;
			return true;
		}
		if (fclose(m_fd) < 0) {
			return false;
		}
		m_fd = NULL;
	}
	return true;
}

size_t FileWriter::write(const void *data, size_t len)
{
	return fwrite(data, 1, len, m_fd);
}

} } // sp::log