#include "StdAfx.h"
#include "CNZSDK.h"
#include "CMyString.h"

CNZSDK::CNZSDK( )
{
	m_eSdkKind = NZ_SDK_NRS;
	m_eNrsSessionType = NZ_SESSION_TYPE_LIVE;
	m_eNrsModel =	NZ_MODEL_RHINO;

	Init( );
}

CNZSDK::~CNZSDK( )
{
	Close( );
}

BOOL CNZSDK::Open( LPCTSTR dll_dir )
{
	if( m_handle )
		return FALSE;
	m_lib = ::LoadLibrary( CMyString(_T("%s\\NZSDK.dll"), dll_dir) );
	if( !m_lib )
		return FALSE;

	switch(m_eSdkKind)
	{
	case NZ_SDK_VMS:
		{
			m_fn_create	= GetProcAddress( m_lib, "NZ_VMS_Create" );
			m_fn_delete	= GetProcAddress( m_lib, "NZ_VMS_Delete" );
			m_fn_command= GetProcAddress( m_lib, "NZ_VMS_Command" );
			m_fn_releasedata = GetProcAddress( m_lib, "NZ_VMS_ReleaseData" );
			m_fn_getlasterror = GetProcAddress( m_lib, "NZ_VMS_GetLastError" );
		}
		break;
	default:
		{
			m_fn_create	= GetProcAddress( m_lib, "NZ_Create" );
			m_fn_create_ex = GetProcAddress( m_lib, "NZ_CreateEx" );
			m_fn_delete	= GetProcAddress( m_lib, "NZ_Delete" );
			m_fn_command= GetProcAddress( m_lib, "NZ_Command" );
		}
		break;
	}

	if( !m_fn_create || !m_fn_delete || !m_fn_command )
		goto FAILED;

	switch(m_eSdkKind)
	{
	case NZ_SDK_VMS:
		m_handle = ((NZ_VMS_CREATE)m_fn_create)();
		break;
	default:
		m_handle = ((NZ_CREATE_EX)m_fn_create_ex)( m_eNrsSessionType, m_eNrsModel );
		break;
	}

	if( !m_handle )
		goto FAILED;
	return TRUE;

FAILED:
	Close( );
	return FALSE;
}

void CNZSDK::Close( )
{
	if( m_lib && m_handle )
	{
		switch(m_eSdkKind)
		{
		case NZ_SDK_VMS:
			((NZ_VMS_DELETE)m_fn_delete)( m_handle );
			break;
		default:
			((NZ_DELETE)m_fn_delete)( m_handle );
			break;
		}
	}
	if( m_lib )
		::FreeLibrary( m_lib );
	Init( );
}

BOOL CNZSDK::Command( NZ_CMD cmd, DWORD_PTR arg1, DWORD_PTR arg2, DWORD_PTR arg3, DWORD_PTR arg4, DWORD_PTR arg5 )
{
	if( !m_lib || !m_handle )
		return FALSE;

	BOOL bResult = FALSE;
	switch(m_eSdkKind)
	{
	case NZ_SDK_VMS:
		bResult = ((NZ_VMS_COMMAND)m_fn_command)( m_handle, cmd, arg1, arg2, arg3, arg4, arg5 );
		break;
	default:
		bResult = ((NZ_COMMAND)m_fn_command)( m_handle, cmd, arg1, arg2, arg3, arg4, arg5 );
		break;
	}

	return bResult;
}

void CNZSDK::Init( )
{
	m_lib = NULL;
	m_handle = NULL;
	m_fn_create = NULL;
	m_fn_create_ex = NULL;
	m_fn_delete = NULL;
	m_fn_command = NULL;
	m_fn_releasedata = NULL;
	m_fn_getlasterror = NULL;
}

DWORD CNZSDK::GetLastError()
{
	if( !m_lib || !m_handle )
		return 0;

	if (m_eSdkKind != NZ_SDK_VMS)
		return 0;

	return ((NZ_VMS_GETLASTERROR)m_fn_getlasterror)( m_handle );
}

void CNZSDK::ReleaseData( LPCSTR pBuffer )
{
	if( !m_lib || !m_handle )
		return;

	if (m_eSdkKind != NZ_SDK_VMS)
		return;

	((NZ_VMS_RELEASEDATA)m_fn_releasedata)( pBuffer );
}