#include "Mix/Tool/CLR/Core/Graphics/MaterialCollection.h"

namespace Mix{ namespace Tool{ namespace Graphics{

MaterialCollection::MaterialCollection( Mix::Tool::Win32::Graphics::MaterialSlot* _impl ) :
impl( _impl )
{
	m_List = gcnew System::Collections::Generic::List<Mix::Tool::Graphics::Material^>();

	for( unsigned int i = 0; i < impl->GetCount(); i++ )
	{
		m_List->Add( gcnew Mix::Tool::Graphics::Material( impl->GetByIndex( i ) ) );
	}
}

MaterialCollection::~MaterialCollection( void )
{
	if( m_List != nullptr )
	{
		for each ( Mix::Tool::Graphics::Material^ item in m_List )
		{
			delete item;
		}

		m_List->Clear();

		delete m_List;
	}

	impl = NULL;
}

int MaterialCollection::Count::get( void )
{
	return m_List->Count;
}

Mix::Tool::Graphics::Material^ MaterialCollection::default::get( int index )
{
	try
	{
		return m_List[index];
	}
	catch( System::Exception^ )
	{
		throw;
	}
}

Mix::Tool::Graphics::Material^ MaterialCollection::default::get( System::String^ name )
{
	for each ( Mix::Tool::Graphics::Material^ material in m_List )
	{
		if( material->Name->Equals( name ) == true )
		{
			return material;
		}
	}

	return nullptr;
}

Mix::Tool::Graphics::Material^ MaterialCollection::ActiveMaterial::get( void )
{
	for each ( Mix::Tool::Graphics::Material^ material in m_List )
	{
		if( material->IsActive == true )
		{
			return material;
		}
	}

	return nullptr;
}

void MaterialCollection::ActiveMaterial::set( Mix::Tool::Graphics::Material^ value )
{
	if( value == nullptr )
	{
		throw gcnew System::ArgumentNullException( L"ActiveMaterial" );
	}

	if( m_List->Contains( value ) == true )
	{
		value->Activate();
	}
}

Mix::Tool::Graphics::Material^ MaterialCollection::Add( void )
{
	Mix::Tool::Graphics::Material^ item = gcnew Mix::Tool::Graphics::Material( impl->Add() );

	m_List->Add( item );

	return item;
}

void MaterialCollection::Remove( Mix::Tool::Graphics::Material^ item )
{
	pin_ptr<const wchar_t> wpName = PtrToStringChars( item->Name );

	impl->Remove( wpName );
	m_List->Remove( item );

	delete item;
}

System::Collections::IEnumerator^ MaterialCollection::GetEnumerator( void )
{
	return m_List->GetEnumerator();
}

}}}
