#include "AdeptHeaders.hpp"
#include "VideoHeaders.hpp"
#include "Tool.hpp"

using namespace ElementRenderer;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
ScalableShapeComponent::ClassData*
	ScalableShapeComponent::CreateFactoryRequest(
		FactoryRequestParameters *parameters
	)
{
	Check_Object(parameters);
	Check_Object(Resource::ParentFileDependencies);

	//
	//-------------------------------------------------------------------------
	// 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(ShapeComponent));

	//
	//------------------------------------
	// Find the parent object for the mesh
	//------------------------------------
	//
	Page *page = parameters->m_page;
	Check_Object(page);

	//
	//-------------------------
	// Deal with the instancing
	//-------------------------
	//
	bool instance = false;
	page->GetEntry("Unique", &instance);
	*component_stream << instance;

	//
	//-----------------------------------------------
	// Check to see if an alpha property is being set
	//-----------------------------------------------
	//
	const char* geometry_name;
	page->GetEntry("Geometry", &geometry_name, true);
	FileStream file_stream(geometry_name);
	const char* file_name = file_stream.GetFileName();

	//
	//----------------------------------------------------------
	// If the resource doesn't need to be built, just get its ID
	//----------------------------------------------------------
	//
	Resource shape_res(file_name);
	if (!shape_res.DoesResourceExist() || !shape_res.IsResourceUpToDate())
	{
		FileDependencies erf_dependencies;
		erf_dependencies.AddDependency(&file_stream);
		shape_res.Save(&file_stream, &erf_dependencies);
		if (!shape_res.IsRegistered())
			Resource::ParentFileDependencies->AddDependencies(&erf_dependencies);
	}
	else if (!shape_res.IsRegistered())
		shape_res.AddFileDependenciesTo(Resource::ParentFileDependencies);
	*component_stream << shape_res.GetResourceID();

	//
	//-----------------------
	// Find the initial scale
	//-----------------------
	//
	bool result = BaseClass::CreateFactoryRequest(parameters) != NULL;
	Scalar scale = 1.0f;
	page->GetEntry("Scale", &scale);
	if (scale < 0.01f)
	{
		STOP((
			"%s: {[%s]Scale=%f}: Scale must be >= 0.01!",
			page->GetNotationFile()->GetFileName(),
			page->GetName(),
			scale
		));
		result = false;
	}
	*component_stream << scale;

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