#include "Mix/Tool/CLR/Core/Dynamics/IdentifierGenerator.h"

namespace Mix{ namespace Tool{ namespace Dynamics{

IdentifierGenerator::IdentifierGenerator( Mix::Tool::Utility::BindingItemCollection<int>^ owner ) :
m_Owner( owner ),
m_Name( gcnew System::String( L"" ) ),
m_RealValue( 0 ),
m_Err( false ),
ValueChanged( nullptr )
{
	if( owner == nullptr )
	{
		throw gcnew System::ArgumentNullException( L"owner" );
	}

	m_Owner->ListChanged += gcnew System::ComponentModel::ListChangedEventHandler( this, &IdentifierGenerator::ListChanged );
}

IdentifierGenerator::~IdentifierGenerator( void )
{
	if( m_Owner != nullptr )
	{
		m_Owner->ListChanged -= gcnew System::ComponentModel::ListChangedEventHandler( this, &IdentifierGenerator::ListChanged );
	}
}

System::String^ IdentifierGenerator::Name::get( void )
{
	return m_Name;
}

void IdentifierGenerator::Name::set( System::String^ value )
{
	if( m_Name->Equals( value ) == false )
	{
		m_Name = value;
		Update();
	}
}

int IdentifierGenerator::Value::get( void )
{
	return m_RealValue;
}

bool IdentifierGenerator::Error::get( void )
{
	return m_Err;
}

void IdentifierGenerator::Update( void )
{
	int index = m_Owner->FindByName( m_Name );

	if( index >= 0 )
	{
		if( int::TryParse( m_Owner[index]->Value, m_RealValue ) == true )
		{
			if( ValueChanged != nullptr )
			{
				ValueChanged( this, gcnew System::EventArgs() );
			}
		}

		m_Err = false;
/*
		m_RealValue = int::Parse( m_Owner[index]->Value );
		m_Err = false;

		if( ValueChanged != nullptr )
		{
			ValueChanged( this, gcnew System::EventArgs() );
		}
*/	}
	else
	{
		m_Err = true;
	}
}

void IdentifierGenerator::ListChanged( System::Object^ sender, System::ComponentModel::ListChangedEventArgs^ e )
{
	Update();
}

}}}
