#include <assert.h>
#include "filesystem/file.h"

static const char* s_stdioOpeningMode[] = { "rb", "wb" };
static int s_stdioSeekDir[] = { SEEK_SET, SEEK_CUR, SEEK_END };

File::File(const char* path, FileAccess access)
{
	m_filehandle = fopen(path, s_stdioOpeningMode[(int)access]);
	assert(m_filehandle && "Unable to open file");
}

File::~File()
{
	if (m_filehandle)
	{
		fclose(m_filehandle);
		m_filehandle = nullptr;
	}
}

void File::seek(SeekDir seekdir, long offset)
{
	fseek(m_filehandle, offset, s_stdioSeekDir[(int)seekdir]);
}

long File::tell()
{
	return ftell(m_filehandle);
}

bool File::eof()
{
	return feof(m_filehandle);
}

size_t File::read(void* buffer, size_t size)
{
	return fread(buffer, 1, size, m_filehandle);
}

size_t File::write(void const* buffer, size_t size)
{
	return fwrite(buffer, size, 1, m_filehandle);
}

void File::readStringBuffer(char* buffer, size_t bufferSize)
{
	seek(SeekDir::End, 0);
	size_t length = tell();
	seek(SeekDir::Begin, 0);

	assert(length <= bufferSize);

	read(buffer, length);
	buffer[length] = '\0';
}
