#include "AdeptHeaders.hpp"

#include "AudioSample.hpp"
#include "Tool.hpp"

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	AudioSample::BuildSoundPool(NotationFile *hint_file)
{
	//
	//-------------------------------
	// Open up the texture build file
	//-------------------------------
	//
	Check_Object(Tool::Instance);
	NotationFile::PageIterator *pages = hint_file->MakePageIterator();
	Register_Object(pages);

	//
	//---------------------------------------------------------
	// Go through the textures file and add each listed texture
	//---------------------------------------------------------
	//
	Check_Object(Tool::Instance);
	Page *page;
	Verify(!Resource::ParentFileDependencies);
	while ((page = pages->ReadAndNext()) != NULL)
	{
		Check_Object(page);
		const char* sound = page->GetName();
		if (!sound)
			continue;
		Check_Pointer(sound);

		//
		//--------------------------
		// Find the file on the path
		//--------------------------
		//
		MString file_name("content\\audio\\");
		file_name += sound;
		Verify(!FileStream::IsRedirected);
		if (!gos_DoesFileExist(file_name))
		{
			PAUSE(("%s could not be found in the audio directory!", (char*)file_name));
			continue;
		}

		//
		//--------------------------------------------------------
		// If not, or it's not up to date, put it in the resources
		//--------------------------------------------------------
		//
		Resource resource((FileStream::IsRedirected)?FileStream::RedirectedName:file_name);
		FileStream::IsRedirected = false;
		if (!resource.DoesResourceExist() || !resource.IsResourceUpToDate())
		{
			FileStream file_name_file(file_name);
			FileDependencies file_name_dependencies;
			file_name_dependencies.AddDependency(&file_name_file);
			file_name_dependencies.AddDependencies(hint_file->GetFileDependencies());
			resource.Save(&file_name_file, &file_name_dependencies);

			//
			//---------------
			// Read the hints
			//---------------
			//
			DynamicMemoryStream stream;
			stream << resource.GetResourceID();

			bool flag=false;
			page->GetEntry("Streamed", &flag);
			stream << (int)((flag)?gosAudio_StreamedFP:gosAudio_UserMemoryDecode);
			flag = !flag;
			page->GetEntry("Cached", &flag);
			stream << flag;
			flag = false;
			page->GetEntry("3D", &flag);
			stream << flag;

			//
			//---------------------------------
			// Open the file as a memory stream
			//---------------------------------
			//
			MString handle_name(file_name);
			handle_name += "{handle}";
			Resource hint(handle_name);
			hint.Save(&stream, hint_file->GetFileDependencies());
		}
	}

	Unregister_Object(pages);
	delete pages;
}
