#include "AdeptHeaders.hpp"

#include "ComponentHeaders.hpp"
#include "EntityClassData.hpp"

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
StateWatcher::ClassData*
	StateWatcher::CreateFactoryRequest(
		FactoryRequestParameters *parameters,
		Entity::ClassData *class_data
	)
{
	Check_Object(parameters);

	bool result = ChannelOf<int>::CreateFactoryRequest(parameters) != NULL;

	//
	//-------------------------
	// Read the attribute field
	//-------------------------
	//
	MemoryStream *component_stream = parameters->m_stream;
	Check_Object(component_stream);
	Page *page = parameters->m_page;
	StateEngine::ClassData *blueprint = NULL;
	const char* attribute_name;
	page->GetEntry("Attribute", &attribute_name, true);
	Check_Object(class_data);
	const AttributeEntry *attribute =
		class_data->attributeTable.GetAttributeEntry(attribute_name);
	if (!attribute)
	{
		STOP((
			"%s: {[%s]Attribute=%s}: Unknown attribute!",
			page->GetNotationFile()->GetFileName(),
			page->GetName(),
			attribute_name
		));
		result = false;
	}

	//
	//-----------------------------------------------
	// Make sure that the attribute is a state engine
	//-----------------------------------------------
	//
	else
	{
		Check_Object(attribute);
		blueprint =
			Cast_Pointer(
				StateEngine::ClassData*,
				FindClassData(attribute->attributeType)
			);
		if (!blueprint)
		{
			STOP((
				"%s: {[%s]Attribute=%s}: Attribute is not a state engine!",
				page->GetNotationFile()->GetFileName(),
				page->GetName(),
				attribute_name
			));
			result = false;
		}
		else
		{
			Check_Object(blueprint);
			*component_stream << attribute->attributeID;
		}
	}

	//
	//-----------------------------------------------
	// Look up the entries for the old and new states
	//-----------------------------------------------
	//
	if (blueprint)
	{
		int state_id = -1;
		const char *state_name;
		const StateEngine::StateEntry* state_entry = NULL;
		if (page->GetEntry("OldState", &state_name))
		{
			state_entry = blueprint->FindStateEntry(state_name);
			if (!state_entry)
			{
				STOP((
					"%s: {[%s]OldState=%s}: Not a valid state name!",
					page->GetNotationFile()->GetFileName(),
					page->GetName(),
					state_name
				));
				result = false;
			}
			else
			{
				state_id = state_entry->stateNumber;
			}
		}
		*component_stream << state_id;
		state_id = -1;
		if (page->GetEntry("NewState", &state_name))
		{
			state_entry = blueprint->FindStateEntry(state_name);
			if (!state_entry)
			{
				STOP((
					"%s: {[%s]NewState=%s}: Not a valid state name!",
					page->GetNotationFile()->GetFileName(),
					page->GetName(),
					state_name
				));
				result = false;
			}
			else
			{
				state_id = state_entry->stateNumber;
			}
		}
		*component_stream << state_id;
	}

	Check_Object(DefaultData);
	return (result) ? DefaultData : NULL;
}
