//
//	Copyright © 2008 Nemetschek North America 
//	All Rights Reserved.
//
// Created by Vladislav Stanev

#include "StdAfx.h"

using namespace VWFC::Math;
using namespace VWFC::VWObjects;

VWBodyObj::VWBodyObj()
{
	fhObject		= nil;
	fp				= NULL;
	fpAPI			= NULL;
	::GS_VWQueryInterface( IID_ParasolidKernel, & fp );
	::GS_VWQueryInterface( IID_ParasolidVWAPI, & fpAPI );
}

VWBodyObj::VWBodyObj(const VWBodyObj& src)
{
	fhObject		= nil;
	fp				= NULL;
	fpAPI			= NULL;

	fhObject		= src.fhObject;
	::GS_VWQueryInterface( IID_ParasolidKernel, & fp );
	::GS_VWQueryInterface( IID_ParasolidVWAPI, & fpAPI );
}

VWBodyObj::VWBodyObj(MCObjectHandle hObj)
{
	fhObject		= nil;
	fp				= NULL;
	fpAPI			= NULL;

	VWFC_ASSERT( VWBodyObj::IsBodyObject( hObj ) );
	if ( ! VWBodyObj::IsBodyObject( hObj ) )
		THROW_VWFC_EXCEPTION( VWBadObjectTypeException, 0, "bad handle type when creating" );
	fhObject		= hObj;
	VWFC_ASSERT( fhObject != nil );

	::GS_VWQueryInterface( IID_ParasolidVWAPI, & fpAPI );
	::GS_VWQueryInterface( IID_ParasolidKernel, & fp );

	if (fpAPI) {
		if (!((IParasolidVWAPI *)fpAPI)->IsValidHandleForBody(fhObject))
			THROW_VWFC_EXCEPTION( VWBadObjectTypeException, 0, "bad handle type when creating" );

		if (!((IParasolidVWAPI *)fpAPI)->GetParasolidBodies(fhObject, false, false, false, true, false, fBodies)) {
			fBodies.clear();
		}
	}
}

VWBodyObj::~VWBodyObj()
{
	fhObject		= nil;
	if ( fpAPI ) {
		fpAPI->Release();
		fpAPI	= NULL;
	}

	if (fp) {
		int size = fBodies.size();
		PK_ENTITY_delete(size, &fBodies[0]);
		fp->Release();
		fp	= NULL;
	}
}

VWBodyObj& VWBodyObj::operator=(const VWBodyObj& src)
{
	fhObject		= src.fhObject;
	return *this;
}

size_t VWBodyObj::GetBodyCount()
{
	return fBodies.size();
}

bool VWBodyObj::GetBody(size_t index, VWBody& outBody)
{
	if (fBodies.size() > 0 && index < fBodies.size()) {
		outBody = VWBody(fBodies[index]);
		return true;
	}

	return false;
}

bool VWBodyObj::IsBodyObject(MCObjectHandle hObj)
{
	short	type	= ::GS_GetObjectType( gCBP, hObj );

	if (type == kSolidNode			|| 
		type == kCSGTreeNode		|| 
		type == kExtrudeNode		||
		type == kSweepNode			||
		type == kMultiExtrudeNode	||
		type == qPolyNode			||
		type == kMeshNode			||
		type == kParametricNode		||
		type == kSymbolNode			||
		type == kSlabNode			||
		type == kNurbsSurfaceNode	||
		type == kWallNode			||
		type == kRoundWallNode		||
		type == kRoofContainerNode	||
		type == kGroupNode)
		return true;

	return false;
}