#include "mof/AmbientLight.hpp"
#include "mof/ConsoleIO.hpp"
#include "mof/private/GraphicsDeviceImpl.hpp"

struct mof::AmbientLight::Impl{
	mof::Color lastAmbient;
	bool enable;

	Impl();
	~Impl();
	void reflect( mof::Color color , bool force = false);
};

mof::AmbientLight::Impl::Impl()
: enable(true)
{
}

mof::AmbientLight::Impl::~Impl(){
	
}

mof::AmbientLight::AmbientLight( mof::Color4f color )
: m_pImpl( new Impl() ) , mof::Light() 
{
	setDiffuseColor(color);
	m_pImpl->reflect( m_diffuseColor->value(m_frame).toColorCode() , true);
}


mof::AmbientLight::~AmbientLight(){
	try{
		setEnable(false);//例外を投げるかも
	}catch(std::exception& ){
	}
}

void mof::AmbientLight::setFrameNumber(mof::FrameNumber frame){
	m_frame = frame;
	m_pImpl->reflect(  m_diffuseColor->value(m_frame).toColorCode() );
	
}

void mof::AmbientLight::nextFrame(){
	setFrameNumber(m_frame + 1);
}

void mof::AmbientLight::prevFrame(){
	if(m_frame > 0)setFrameNumber(m_frame - 1);
}


void mof::AmbientLight::setEnable(bool enable){
	if(!m_pImpl->enable && enable){
		m_pImpl->enable = enable;
		m_pImpl->reflect(  m_diffuseColor->value(m_frame).toColorCode() );
	}
	else if(m_pImpl->enable && !enable){
		m_pImpl->enable = enable;
		m_pImpl->reflect( m_diffuseColor->value(m_frame).toColorCode() );
	}
}


void mof::AmbientLight::Impl::reflect(mof::Color color , bool force){
	//複数のアンビエントをサポートするべき
	mof::Color ambient = color;
	if(!enable)ambient = mof::createColor(0 , 0 , 0);

	if(ambient != lastAmbient || force){
		mof::GraphicsDevice::getRawDevice()->SetRenderState(D3DRS_AMBIENT , ambient);
		lastAmbient = ambient;
	}
}

