#include "Win32WicImageWriter.h"

#include "Image.h"
#include "Win32WicInterface.h"
#include "Win32WicImage.h"
#include "StringUtils.h"
#include "Directory.h"

#include <wincodec.h>
#include <wrl.h>

Win32WicImageWriter::Win32WicImageWriter(ImgFormat format)
	: PlatformImageWriter(format)
{

}

void Win32WicImageWriter::write(const Path& path, Image* image)
{
	Directory::createIfNotExisting(path);

	Win32WicInterface wic_interface;

	Microsoft::WRL::ComPtr<IWICStream> pStream;
	auto hr = wic_interface.getFactory()->CreateStream(&pStream);

	hr = pStream->InitializeFromFilename(path.wstring().c_str(), GENERIC_WRITE);

	Microsoft::WRL::ComPtr<IWICBitmapEncoder> pEncoder;
	hr = wic_interface.getFactory()->CreateEncoder(GUID_ContainerFormatPng, nullptr, &pEncoder);

	hr = pEncoder->Initialize(pStream.Get(), WICBitmapEncoderNoCache);

	Microsoft::WRL::ComPtr<IWICBitmapFrameEncode> pFrameEncode;
	hr = pEncoder->CreateNewFrame(&pFrameEncode, nullptr);

	hr = pFrameEncode->Initialize(nullptr);

	hr = pFrameEncode->SetSize(image->getWidth(), image->getHeight());

	WICPixelFormatGUID out_format = GUID_WICPixelFormatDontCare;
	hr = pFrameEncode->SetPixelFormat(&out_format);

	hr = pFrameEncode->WriteSource(dynamic_cast<Win32WicImage*>(image->getPlatformImage())->getBitmap(), nullptr);

	hr = pFrameEncode->Commit();

	hr = pEncoder->Commit();
}
