#include "E3DLightManager.h"

#include <easy3d.h>
#include "HPLException.h"

namespace HPL {
namespace E3D {

using namespace General;

LightData::LightData(int nLightID, D3DXVECTOR3& vDirection, E3DCOLOR4UC& cColor) {
	this->m_nLightID = nLightID;
	memcpy(&this->m_vDirection, &vDirection, sizeof(D3DXVECTOR3) );
	memcpy(&this->m_cColor, &cColor, sizeof(E3DCOLOR4UC ) );
}
LightData::~LightData() {
}

E3DLightManager::E3DLightManager() {
}

void freeMap( std::map<int, LightData*>* lpLightDataMap) {
	for(std::map<int, LightData*>::iterator it = lpLightDataMap->begin();
		it != lpLightDataMap->end(); it ++ )
	{
		std::pair<int, LightData*> p = *it;
		delete p.second;
		p.second = NULL;
	}
	lpLightDataMap->clear();
}
E3DLightManager::~E3DLightManager() {
	freeMap(&this->m_mapLightDataMap );
	freeMap( &this->m_mapMasterLightDataMap );
}

int E3DLightManager::create( int nUserID, D3DXVECTOR3& vDirection, E3DCOLOR4UC& cColor ) {
	if(this->m_mapLightDataMap.find(nUserID) != this->m_mapLightDataMap.end() ) {
		_ASSERT( 0 );
		throw HPLException( -1, "light id[%d] already exists", nUserID );
	}

	int nID = 0;
	int ret = E3DCreateLight( &nID );

	if( ret != 0 ) {
		_ASSERT( 0 );
		return -1;
	}

	LightData* lightData = new LightData( nID, 
		vDirection, cColor);
	LightData* masterLightData = new LightData( nID,
		vDirection, cColor);

	this->m_mapMasterLightDataMap[nUserID] = lightData;
	this->m_mapLightDataMap[nUserID] = masterLightData;

	if( E3DSetDirectionalLight( nID, vDirection, cColor ) != 0 ) {
		_ASSERT( 0 );
		return 1;
	}

	return 0;
}


/**
  * @param[in] 
  * @exception HPLException* 存在しないIDを指定したとき
  */
LightData* E3DLightManager::get_LightData( int id ) {
	if(this->m_mapLightDataMap.find(id) == this->m_mapLightDataMap.end() ) {
		_ASSERT( 0 );
		throw HPLException( -1, "light id[%d] not found", id );
	}

	return this->m_mapLightDataMap[id];
}

}
}
