#include "NativeAssetFile.h"
#include "FilePath.h"

#include <android_native_app_glue.h>
#include <sstream>
#include <stdexcept>

//////////////////////////////////////////////////////////////
namespace Dubious {
namespace Utility {

NativeAssetFile::NativeAssetFile( AAssetManager& Manager, const FilePath& Path )
{
	m_pFile = AAssetManager_open( &Manager, Path.FullPath().c_str(), AASSET_MODE_BUFFER );
	if (!m_pFile) {
	    throw std::runtime_error( "Failed to open asset: " + Path.FullPath() );
	}
}

NativeAssetFile::~NativeAssetFile()
{
	AAsset_close(m_pFile);
}

std::string NativeAssetFile::Read()
{
	const int BUFFER_SIZE=1024;
	char Buffer[BUFFER_SIZE];
	int Count;
	std::stringstream Result;

	// Read the file contents in a loop
	while (((Count = AAsset_read(m_pFile, Buffer, BUFFER_SIZE)) > 0)) {
	    Result.write( Buffer, Count );
	}
	return Result.str();
}

size_t NativeAssetFile::Read( unsigned char* Buffer, size_t ByteCount )
{
	return AAsset_read( m_pFile, Buffer, ByteCount );
}

}
}
