#include "bt_mp_dll_build.h"
#include <stdio.h>

static pfBTMPAPI_BuildBluetoothModule hfBTMPAPI_BuildBluetoothModule=NULL;
static pfBTMPAPI_BuildInterfaceVendor hfBTMPAPI_BuildInterfaceVendor=NULL;
static pfBTMPAPI_BuildInterfaceRTK hfBTMPAPI_BuildInterfaceRTK=NULL;

#ifndef BCB_MODE
static HMODULE hRTKBTMPDLL_Object=NULL;
#else
#include <vcl.h>
#pragma hdrstop
static HINSTANCE hRTKBTMPDLL_Object=NULL;
#endif




static int LoadRTKBTMPDLLObject(char *DllModulePathBuffer);
static void UnLoadLoadRTKBTMPDLLObject();

static int LoadRTKBTMPDLLObject(char *DllModulePathBuffer)
{
	char DLLPathBuffer[700];
	//int szLen=0;
	memset(DLLPathBuffer,0,700);
   
#ifdef _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
	if (strlen(DllModulePathBuffer)== 0)
		sprintf(DLLPathBuffer,_T"RTLBlueToothMP.dll");
	else
		sprintf(DLLPathBuffer,_T"%s\\RTLBlueToothMP.dll",DllModulePathBuffer);
#else

	if (strlen(DllModulePathBuffer)== 0)
		sprintf(DLLPathBuffer,"RTLBlueToothMP.dll");
	else
		sprintf(DLLPathBuffer,"%s\\RTLBlueToothMP.dll",DllModulePathBuffer);
#endif
	hRTKBTMPDLL_Object = LoadLibrary(DLLPathBuffer);
	if (hRTKBTMPDLL_Object == NULL)
		return -1;

	hfBTMPAPI_BuildBluetoothModule	=(pfBTMPAPI_BuildBluetoothModule)	GetProcAddress(hRTKBTMPDLL_Object,"BTMPAPI_BuildBluetoothModule");
	hfBTMPAPI_BuildInterfaceVendor	=(pfBTMPAPI_BuildInterfaceVendor)   GetProcAddress(hRTKBTMPDLL_Object,"BTMPAPI_BuildInterfaceVendor");
	hfBTMPAPI_BuildInterfaceRTK	=(pfBTMPAPI_BuildInterfaceRTK)	        GetProcAddress(hRTKBTMPDLL_Object,"BTMPAPI_BuildInterfaceRTK");

#ifndef _IsVCType_
	atexit(UnLoadLoadRTKBTMPDLLObject);
#endif
	if ((hfBTMPAPI_BuildBluetoothModule== NULL) ||
		(hfBTMPAPI_BuildInterfaceVendor== NULL)||
		(hfBTMPAPI_BuildInterfaceRTK== NULL)
		)
	{
		return -1;
	}
	return 0;
}



static void UnLoadLoadRTKBTMPDLLObject(void)
{
	if (hRTKBTMPDLL_Object != NULL) 
	FreeLibrary(hRTKBTMPDLL_Object);
	return;
}



void ReleaseBTPMPDLLObject(BASE_BTMPDLLObject *Modlue)
{
	if ((hRTKBTMPDLL_Object == NULL) || (Modlue == NULL))
	{
		return;
	}
	else
	{
		FreeLibrary(hRTKBTMPDLL_Object);
		hRTKBTMPDLL_Object=NULL;
	}

	return;

}



int BuildBTMPDLLObject(BASE_BTMPDLLObject *Modlue,char *SettingPath)
{
	char ModulePathBuffer[256];
	int SettingPathLen=0;
	int n=0;
	memset(ModulePathBuffer,0,256);
	if (Modlue == NULL)
		return -1;

	if (SettingPath != NULL)
		SettingPathLen=strlen(SettingPath);

	if (SettingPathLen>0)
	{
		//memcpy(ModulePathBuffer,SettingPath,SettingPathLen);
		for (n=0;n<SettingPathLen;n++)
		{
			ModulePathBuffer[n]= SettingPath[n];
		}
	}
	if (hRTKBTMPDLL_Object == NULL){
		if (LoadRTKBTMPDLLObject(ModulePathBuffer) !=0)
		{
			ReleaseBTPMPDLLObject(Modlue);
			return -1;
		}
	}

	Modlue->BTMPAPI_BuildBluetoothModule= hfBTMPAPI_BuildBluetoothModule;
	Modlue->BTMPAPI_BuildInterfaceRTK=  hfBTMPAPI_BuildInterfaceRTK;
	Modlue->BTMPAPI_BuildInterfaceVendor= hfBTMPAPI_BuildInterfaceVendor;
	return 0;
}


