#include "gamesrv.h"

#include "stdafx.h"
#include "Npc.h"
#include "ObjectManager.h"
#include "NpcScript.h"

#include "player.h"

cNpc::cNpc(void) : cBaseObject( eOBJECTTYPE_NPC )
{
}

cNpc::~cNpc(void)
{
}

void* cNpc::operator new( size_t n )
{
	if( n != sizeof(cNpc) ) 
	{
		assert(0);
		return NULL;
	}

	return OBJECTMANAGER->AllocNpc();
}

void cNpc::operator delete( void* ptr, size_t n )
{
	/// NULL 포인터 검사
	if( ptr == 0 )
	{
		assert(0);
		return;
	}

	if( n != sizeof(cNpc) ) 
	{
		assert(0);
		return;
	}

	OBJECTMANAGER->FreeNpc( static_cast<cNpc*>(ptr) );

	return;
}

bool cNpc::Init( int uniqueIdx )
{
	/// NPC 맵 리젠 정보
	sNPCRegen* pNpcRegenScript = NPCSCRIPT->GetNPCRegen( uniqueIdx );
	if ( !pNpcRegenScript )	
	{ 
		assert(NULL);
		NETWORK2->PostServerEvent( "cNpc::Init GetNPCRegen( %d ) = NULL", uniqueIdx );
		return false; 
	}

	mNpcRegen = *pNpcRegenScript;

	/// 고유번호 등록
	mObject.index = uniqueIdx;

	SetMapNumber( pNpcRegenScript->mMapNumber );

	/// 몬스터 리스트 정보
	sNPCList* pNpcListScript = NPCSCRIPT->GetNPCList( pNpcRegenScript->mNpcClassIdx );
	if ( !pNpcListScript )	
	{ 
		assert(NULL);
		NETWORK2->PostServerEvent( "cNpc::Init GetNPCList( %d ) = NULL", pNpcRegenScript->mNpcClassIdx );
		return false; 
	}

	mpNpcList = pNpcListScript;

	SetPos( mNpcRegen.mPosX, mNpcRegen.mPosY );
	return true;
}

// GetNpcData Method
void cNpc::GetNpcData( cPlayer* player, sNpcData* npcData )
{
	npcData->mNpcIdx      = mObject.index;						// 070627 PKH NPC 고유번호
	npcData->mNpcClassIdx = mpNpcList->mNpcClassIdx;			// 070627 PKH NPC 종류
	npcData->mPosX        = mObjectPos.x;						// 070627 PKH NPC x좌표
	npcData->mPosY        = mObjectPos.y;						// 070627 PKH NPC y좌표
	npcData->mDirection   = mNpcRegen.mDirection;				// 070627 PKH NPC 방향

	eNpcQuestStatus status = eNPCQUEST_NONE;
	player->GetQuestStatus( status, mObject.index );
	npcData->mQuestStatus = status;
}

// SendSightIn Method
bool cNpc::SendSightIn(char category, char protocol, cPlayer* player )
{
	HANDLE        handle  = NULL;
	MSG_NPC_INFO* sendMsg = (MSG_NPC_INFO*)NETWORK2->GetMsgRoot( &handle, player->GetConnectionIdx( ) );
	if ( sendMsg != NULL )
	{
		sNpcData* npcData = sendMsg->mNpcInfo;

		sendMsg->Category = category;
		sendMsg->Protocol = protocol;
		sendMsg->mCount   = 1;

		GetNpcData( player, npcData );

		return NETWORK2->SendMsgRoot( handle, sendMsg->GetMsgLength( ) );
	}
	return false;
}

// SendSightOut Method
bool cNpc::SendSightOut(char category, char protocol, unsigned long connectionIdx)
{
	HANDLE      handle  = NULL;
	MSG_NPCIDX* sendMsg = (MSG_NPCIDX*)NETWORK2->GetMsgRoot( &handle, connectionIdx );
	if ( sendMsg != NULL )
	{
		sendMsg->Category = category;
		sendMsg->Protocol = protocol;
		sendMsg->mNpcIdx  = mObject.index; // GetObjectID Method

		return NETWORK2->SendMsgRoot( handle, sizeof(MSG_NPCIDX) );
	}
	return false;
}
