#include "Win32TempFile.h"

#include "FileLogger.h"

Win32TempFile::Win32TempFile()
{
    if (::GetTempFileName(L".", L"New", 0, &mName[0]) == 0)
    {
        auto result = ::GetLastError();
        MLOG_ERROR("Failed to set up temp file for buffer with: " << result);
        return;
    }

    mHandle = ::CreateFile(&mName[0], GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (mHandle == INVALID_HANDLE_VALUE)
    {
        auto result = ::GetLastError();
        MLOG_ERROR("Failed to create temp file for buffer with: " << result);
        return;
    }
    mIsValid = true;
    return;
}

Win32TempFile::~Win32TempFile()
{
    if (INVALID_HANDLE_VALUE != mHandle)
    {
        ::CloseHandle(mHandle);
        ::DeleteFile(&mName[0]);
    }
}

void Win32TempFile::write(PUCHAR buffer, ULONG size)
{
    if (!mIsValid)
    {
        return;
    }

    ULONG temp_file_bytes_written = 0;
    ::WriteFile(mHandle, buffer, size, &temp_file_bytes_written, nullptr);
}

HANDLE Win32TempFile::getHandle() const
{
    return mHandle;
}

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