#include "AdeptHeaders.hpp"

#include "ComponentHeaders.hpp"

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
SmootherOf<Scalar>::ClassData*
	SmootherOf<Scalar>::CreateFactoryRequest(
		FactoryRequestParameters *parameters
	)
{
	Check_Object(parameters);

	//
	//-------------------------------------------------------------------------
	// Allocate enough room for what we need to write out, then call our parent
	//-------------------------------------------------------------------------
	//
	MemoryStream *component_stream = parameters->m_stream;
	Check_Object(component_stream);
	component_stream->AllocateBytes(sizeof(SmootherOf<Scalar>));
	bool result =
		ChannelOf<Scalar>::CreateFactoryRequest(parameters) != NULL;

	//
	//-------------------------------
	// Find the input channel to read
	//-------------------------------
	//
	Page *page = parameters->m_page;
	Check_Object(page);
	DynamicArrayOf<ComponentDescriptor> *list = parameters->m_components;
	Check_Pointer(list);
	const char* input_name;
	page->GetEntry("Input", &input_name, true);
	int input_id = ComponentDescriptor::FindName(list, parameters->m_index, input_name);
	if (input_id == -1)
	{
		STOP((
			"%s: {[%s]Input=%s}: Unknown component name!",
			page->GetNotationFile()->GetFileName(),
			page->GetName(),
			input_name
		));
		result = false;
	}
	else
	{
		Component::ClassData* derivation = (*list)[input_id].m_classData;
		Check_Object(derivation);
		if (!derivation->IsDerivedFrom(ChannelOf<Scalar>::DefaultData))
		{
			STOP((
				"%s: {[%s]Input=%s}: Not a Scalar channel!",
				page->GetNotationFile()->GetFileName(),
				page->GetName(),
				input_name
			));
			result = false;
		}
		else
		{
			*component_stream << input_id;
		}
	}

	//
	//---------------------
	// Read the buffer size
	//---------------------
	//
	int buffer_size;
	if (!page->GetEntry("BufferSize", &buffer_size))
	{
		PAUSE((
			"%s: [%s]BufferSize entry is missing!",
			page->GetNotationFile()->GetFileName(),
			page->GetName()
		));
		result = false;
	}
	else if (buffer_size <= 0)
	{
		PAUSE((
			"%s: {[%s]BufferSize=%d}: Buffer Size must be greater than 0!",
			page->GetNotationFile()->GetFileName(),
			page->GetName(),
			buffer_size
		));
		result = false;
	}
	else
	{
		*component_stream << buffer_size;
	}

	//
	//-----------------------
	// Read the initial value
	//-----------------------
	//
	Scalar filler;
	if (!page->GetEntry("InitialValue", &filler))
	{
		PAUSE((
			"%s: [%s]InitialValue entry is missing!",
			page->GetNotationFile()->GetFileName(),
			page->GetName()
		));
		result = false;
	}
	else
	{
		*component_stream << filler;
	}

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