#include "GdiplusWrapper.h"
#include <shlwapi.h>
#include <stdio.h>
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "Shlwapi.lib")
#pragma warning(disable:4996)

CGdiplusWrapper::~CGdiplusWrapper()
{
	ReleaseGdiplus();
}

CGdiplusWrapper & CGdiplusWrapper::GetInstance()
{
	static CGdiplusWrapper obj;
	return obj;
}

Gdiplus::Image* CGdiplusWrapper::LoadImage(wchar_t *szImgPath)
{
	if (!PathFileExistsW(szImgPath)) return NULL;
	Gdiplus::Image* pImg = new Gdiplus::Image(szImgPath);
	if (Gdiplus::Ok == pImg->GetLastStatus())
		return pImg;
	return NULL;
}

bool CGdiplusWrapper::SaveImage(wchar_t *szImgPath, Gdiplus::Image *pImg, wchar_t* szImgType)
{
	if (!pImg) return false;
	const int nlength = 10;
	wchar_t szExt[nlength] = {0};
	if (szImgType)
		swprintf(szExt, L".%s", szImgType);
	else
		_wsplitpath(szImgPath, NULL, NULL, NULL, szExt);
	if (0 == wcscmp(szExt, L".jpg"))
	{
		memset(szExt, 0, sizeof(wchar_t)*nlength);
		wcscpy(szExt, L".jpeg");
	}
	wchar_t szFormat[25] = {0};
	swprintf(szFormat, L"image/%s", &szExt[1]);
	CLSID encoderClsid;
	GetEncoderClsid(szFormat, &encoderClsid);
	if (Gdiplus::Ok == pImg->Save(szImgPath, &encoderClsid)) {
		return true;
	}
	return false;
}

CGdiplusWrapper::CGdiplusWrapper()
{
	InitGdiplus();
}

void CGdiplusWrapper::InitGdiplus()
{
	Gdiplus::GdiplusStartupInput gdiplusstartupinput;
	Gdiplus::GdiplusStartup(&gdiplustoken, &gdiplusstartupinput, NULL);
	Gdiplus::Bitmap bmp(L"xaxfadf.png") ;
	Gdiplus::Image img(L"axax.png");
}

void CGdiplusWrapper::ReleaseGdiplus()
{
	Gdiplus::GdiplusShutdown(gdiplustoken);
}

int CGdiplusWrapper::GetEncoderClsid(const wchar_t* format, CLSID* pClsid)
{
	UINT  num = 0;          // number of image encoders
	UINT  size = 0;         // size of the image encoder array in bytes
	Gdiplus::ImageCodecInfo* pImageCodecInfo = NULL;
	Gdiplus::GetImageEncodersSize(&num, &size);
	if (size == 0) return -1;  // Failure
	pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size));
	if (pImageCodecInfo == NULL) return -1;  // Failure
	Gdiplus::GetImageEncoders(num, size, pImageCodecInfo);
	for (UINT j = 0; j < num; ++j) {
		if (wcscmp(pImageCodecInfo[j].MimeType, format) == 0) {
			*pClsid = pImageCodecInfo[j].Clsid;
			free(pImageCodecInfo);
			return j;  // Success
		}
	}
	free(pImageCodecInfo);
	return -1;  // Failure
}