#include "stdafx.h"
#include "SDLExt.h"

#include "../SDL_Include.h"

#include <cassert>



class LibTiffExtImpl
{
private:
	typedef void (*TIFFErrorHandler)(const char*, const char*, va_list);

private:
	void* DllHandle;
	TIFFErrorHandler (*TIFFSetWarningHandler)(TIFFErrorHandler);
	TIFFErrorHandler PrevHandler;

public:
	LibTiffExtImpl(void)
	{
		DllHandle = NULL;
		TIFFSetWarningHandler = NULL;
		PrevHandler = NULL;

		InitDll();
	}

	~LibTiffExtImpl(void)
	{
		if (DllHandle == NULL)
			return;

		SDL_UnloadObject(DllHandle);
	}

	void BeginDisableWarningMsg(void)
	{
		assert(PrevHandler == NULL);
		if (TIFFSetWarningHandler == NULL)
			return;

		PrevHandler = TIFFSetWarningHandler(NULL);
	}

	void EndDisableWarningMsg(void)
	{
		if (TIFFSetWarningHandler == NULL)
			return;

		TIFFSetWarningHandler(PrevHandler);
		PrevHandler = NULL;
	}

private:
	void InitDll(void)
	{
		void *handle = SDL_LoadObject("libtiff-5.dll");
		if (handle == NULL)
			return;

		DllHandle = handle;
		TIFFSetWarningHandler = (TIFFErrorHandler (*)(TIFFErrorHandler))SDL_LoadFunction(handle, "TIFFSetWarningHandler");
	}
};


void LibTiffExt::BeginDisableWarningMsg(void)
{
	Instance().BeginDisableWarningMsg();
}

void LibTiffExt::EndDisableWarningMsg(void)
{
	Instance().EndDisableWarningMsg();
}

LibTiffExtImpl& LibTiffExt::Instance(void)
{
	static LibTiffExtImpl obj;
	return obj;
}
