#include "Win32Buffer.h"

#include "FileLogger.h"

#ifndef UNICODE
#define UNICODE
#endif

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>

Win32Buffer::Win32Buffer(unsigned size)
{
    createBuffer(size);
}

Win32Buffer::~Win32Buffer()
{
    clearBuffer();
}

unsigned char* Win32Buffer::getBufferAsUChar() const
{
    return reinterpret_cast<unsigned char*>(mBuffer);
}

void* Win32Buffer::getBuffer() const
{
    return mBuffer;
}

bool Win32Buffer::isValid() const
{
	return mIsValid;
}

void Win32Buffer::createBuffer(unsigned size)
{
    mIsValid = false;
    mBuffer = ::HeapAlloc(::GetProcessHeap(), 0, size);
    if (mBuffer == nullptr)
    {
        MLOG_ERROR("Insufficient resources");
        return;
    }
    mIsValid = true;
}

void Win32Buffer::clearBuffer()
{
    if (mBuffer)
    {
        ::HeapFree(::GetProcessHeap(), 0, mBuffer);
    }
}

void Win32Buffer::reset(unsigned size)
{
    clearBuffer();
    createBuffer(size);
}