#include "DirectX2dInterface.h"

#include "DirectXInterface.h"

#include "FileLogger.h"

#include <dxgi.h>
#include <d2d1_3.h>
#include <d2d1_1.h>
#include <dwrite.h>

DirectX2dInterface::DirectX2dInterface(DirectXInterface* dxInterface)
	: mDxInterface(dxInterface)
{

}

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

ID2D1Factory3* DirectX2dInterface::getFactory() const
{
	return mFactory.Get();
}

IDWriteFactory* DirectX2dInterface::getDirectWriteFactory() const
{
	return mDWriteFactory.Get();
}

ID2D1DeviceContext2* DirectX2dInterface::getContext() const
{
	return mDeviceContext.Get();
}

ID2D1RenderTarget* DirectX2dInterface::getRenderTarget() const
{
	if (mRenderTarget)
	{
		return mRenderTarget.Get();
	}
	else
	{
		return mDeviceContext.Get();
	}
}

void DirectX2dInterface::initialize(IWICBitmap* bitmap, bool useSoftware)
{
	D2D1_FACTORY_OPTIONS d2dFactoryOptions = {};
	D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory3), &d2dFactoryOptions, &mFactory);

	auto hr = mFactory->CreateWicBitmapRenderTarget(bitmap, D2D1::RenderTargetProperties(), &mRenderTarget);

	initializeDirectWrite();
}

bool DirectX2dInterface::initialize(IDXGIDevice* device)
{
	D2D1_FACTORY_OPTIONS d2dFactoryOptions = {};
	D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory3), &d2dFactoryOptions, &mFactory);

	mFactory->CreateDevice(device, &mDevice);

	D2D1_DEVICE_CONTEXT_OPTIONS deviceOptions = D2D1_DEVICE_CONTEXT_OPTIONS_NONE;
	mDevice->CreateDeviceContext(deviceOptions, &mDeviceContext);

	return initializeDirectWrite();
}

bool DirectX2dInterface::initializeDirectWrite()
{
	return SUCCEEDED(::DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), &mDWriteFactory));
}