// winlist.cpp : Defines the entry point for the DLL application.
//

# pragma warning( disable : 4786 )

#include "winlist.h"

# include <map>

# include <iostream>

# include <string>

using namespace std;

map< string, callback_method_t > _aCallback;

string g_sCurrentInvocationContext;

string g_sCallbackMethodName;

BOOL __stdcall ListWindows(
	HWND hwnd,
	LPARAM lParam )
{
	char szNum[ 50 ];
	_ultoa( (DWORD) hwnd, szNum, 10 );

	char szCaption[ 1000+1+1 ];
	GetWindowText( hwnd, szCaption, 1000 );

	char szClass[ 1000+1+1 ];
	GetClassName( hwnd, szClass, 1000 );

# if 0 // ifdef _DEBUG
	cerr << "Performing callback, context: " << g_sCurrentInvocationContext.c_str() << ", method: " << g_sCallbackMethodName.c_str() << endl;
# endif

	callback_method_t CallbackMethod = _aCallback[ g_sCurrentInvocationContext ];

	GLOBALHANDLE gh =
		CallbackMethod(
			g_sCurrentInvocationContext.c_str(),
			g_sCallbackMethodName.c_str(),
			szNum,
			szCaption,
			szClass,
			NULL );

	if( gh )
		GlobalFree( gh );

	return TRUE;
}

extern "C"
{
	WINLIST_API GLOBALHANDLE WINAPI Initialize( LPCSTR invocationContext, LPCSTR pOther, ... )
	{
		return 0;
	}

	WINLIST_API void WINAPI SetCallback( LPCSTR invocationContext, callback_method_t CallbackMethod, ... )
	{
		_aCallback[ invocationContext ] = CallbackMethod;
	}

	WINLIST_API GLOBALHANDLE WINAPI List( LPCSTR invocationContext, LPCSTR pCallbackMethodName, ... )
	{
		g_sCurrentInvocationContext = invocationContext;

		g_sCallbackMethodName = pCallbackMethodName;

		EnumWindows( (WNDENUMPROC) ListWindows, 0 );

		return 0;
	}

	WINLIST_API void WINAPI Terminate( LPCSTR invocationContext, ... )
	{
		_aCallback.erase( invocationContext );
	}
};


