//////////////////////////////////////////////////////////////////////////////
//
// Asura_DLC_System.cpp
//
// Copyright (c) 2009 Rebellion. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////

// I N C L U D E S ///////////////////////////////////////////////////////////

#include "Core/Asura.h"

#ifdef ASURA_SUPPORT_DOWNLOADABLE_CONTENT

#include "Network/Asura_DLC_System.h"


Asura_TemplateHashTree<Asura_DLC_DownloadedFileData*> Asura_DLC_System::s_xDLCFiles;


void Asura_DLC_System::Initialise()
{
	Platform_Initialise();

	// Intentionally not calling the tree update at this point, we want to leave it to projects to update at a time that is suitable for them.
}

void Asura_DLC_System::Shutdown()
{
	ClearDownloadedFileData();

	Platform_Shutdown();
}

void Asura_DLC_System::UpdateDownloadedFiles()
{
	// Clear the tree first as the platform function is going to fill it in.
	ClearDownloadedFileData();

	Platform_UpdateDownloadedFiles();
}

bool Asura_DLC_System::IsNewContentAvailable()
{
	return Platform_IsNewContentAvailable();
}

void Asura_DLC_System::OpenStore()
{
	Platform_OpenStore();
}

bool Asura_DLC_System::IsDownloadedFile(const char* szFile)
{
	// Files are stored in the tree without a leading slash, so remove it if this filename has one.
	if (!szFile) { return false; }
	const char* szTestName = (szFile[0] == '/') || (szFile[0] == '\\') ? &(szFile[1]) : szFile;
	return (s_xDLCFiles.GetDataByName(szTestName) != NULL);
}

u_int Asura_DLC_System::GetUsageRestrictions(const char* szFile)
{
	Asura_DLC_DownloadedFileData* const* ppxData = s_xDLCFiles.GetDataByName(szFile);
	if (ppxData && *ppxData)
	{
		return (*ppxData)->GetUsageRestrictions();
	}
	else
	{
		// Not a downloaded file, return unrestricted.
		return 0;
	}
}

const Asura_DLC_DownloadedFileData* Asura_DLC_System::GetDownloadedFileData(const char* szFile)
{
	Asura_DLC_DownloadedFileData* const* ppxData = s_xDLCFiles.GetDataByName(szFile);
	if (ppxData)
	{
		return *ppxData;
	}
	else
	{
		// Not a downloaded file.
		return NULL;
	}
}

void Asura_DLC_System::ClearDownloadedFileData()
{
	// Specific platforms may have additional details to clear outside of the structures deleted below (e.g. on 360 we need to close the virtual drives we've mapped). Let them do that first.
	Platform_ClearDownloadedFileData();

	// Delete all file data pointers, then empty the tree.
	s_xDLCFiles.Traverse(ClearDownloadedFileData_Callback);
	s_xDLCFiles.Reset();
}

void Asura_DLC_System::ClearDownloadedFileData_Callback(Asura_Hash_ID uHash, Asura_DLC_DownloadedFileData** ppxData)
{
	if (ppxData)
	{
		delete (*ppxData);
		(*ppxData) = NULL;
	}
}

#endif //#ifdef ASURA_SUPPORT_DOWNLOADABLE_CONTENT
