#include "PajaTypes.h"
#include "Vector3C.h"
#include <vector>
#include "ScenegraphItemI.h"


using namespace PajaTypes;
using namespace FileIO;


ScenegraphItemI::ScenegraphItemI()
{
	// empty
}


ScenegraphItemI::~ScenegraphItemI()
{
	for( uint32 i = 0; i < m_rChilds.size(); i++ )
		delete m_rChilds[i];
}

void
ScenegraphItemI::add_child( ScenegraphItemI* pChild )
{
	if( pChild )
		m_rChilds.push_back( pChild );
}

uint32
ScenegraphItemI::get_child_count()
{
	return m_rChilds.size();
}

ScenegraphItemI*
ScenegraphItemI::get_child( uint32 ui32Index )
{
	if( ui32Index >= 0 && ui32Index < m_rChilds.size() )
		return m_rChilds[ui32Index];
	return 0;
}

void
ScenegraphItemI::remove_child( uint32 ui32Index )
{
	if( ui32Index >= 0 && ui32Index < m_rChilds.size() )
		m_rChilds.erase( m_rChilds.begin() + ui32Index );
}

void
ScenegraphItemI::set_id( uint32 ui32ID )
{
	m_ui32ID = ui32ID;
}

uint32
ScenegraphItemI::get_id() const
{
	return m_ui32ID;
}

void
ScenegraphItemI::set_name( const char* szName )
{
	m_sName = szName;
}

const char*
ScenegraphItemI::get_name()
{
	return m_sName.c_str();
}

void
ScenegraphItemI::set_parent_name( const char* szName )
{
	m_sParentName = szName;
}

const char*
ScenegraphItemI::get_parent_name()
{
	return m_sParentName.c_str();
}

void
ScenegraphItemI::set_tm( const Matrix3C& rMat )
{
	m_rTM = rMat;
}

const Matrix3C&
ScenegraphItemI::get_tm()
{
	return m_rTM;
}


enum CameraChunksE {
	CHUNK_CGITEM_BASE			= 0x1000,
};

const uint32	CGITEM_VERSION = 1;

uint32
ScenegraphItemI::save( SaveC* pSave )
{
	uint32	ui32Error = IO_OK;

	// camera base
	pSave->begin_chunk( CHUNK_CGITEM_BASE, CGITEM_VERSION );
		// write name
		std::string	sStr( m_sName );
		if( sStr.size() > 255 )
			sStr.resize( 255 );
		ui32Error = pSave->write_str( sStr.c_str() );
	pSave->end_chunk();

	return ui32Error;
}

uint32
ScenegraphItemI::load( LoadC* pLoad )
{
	uint32	ui32Error = IO_OK;
	char	szStr[256];

	while( (ui32Error = pLoad->open_chunk()) == IO_OK ) {

		switch( pLoad->get_chunk_id() ) {
		case CHUNK_CGITEM_BASE:
			{
				if( pLoad->get_chunk_version() == CGITEM_VERSION ) {
					// read name
					ui32Error = pLoad->read_str( szStr );
					m_sName = szStr;
				}
			}
			break;

		default:
			assert( 0 );
		}

		pLoad->close_chunk();

		if( ui32Error != IO_OK && ui32Error != IO_END ) {
			return ui32Error;
		}
	}

	return ui32Error;
}
