/** @file basetypejsonparser.cpp
 *  Functionality for parsing JSON into generic EA::Types classes
 * 	@headerfile basetypejsonparser.h "EABaseTypesJson/basetypejsonparser.h"
 *	@author Chris Burns (cburns@ea.com)
 *
 *	UX
 *	(c) 2012 Electronic Arts Inc. 
 */

#include "EABaseTypesJson/basetypejsonparser.h"

#include "EABaseTypes/factory.h"
#include "EABaseTypes/basetypeencoder.h"

#include "EABaseTypesJson/jsonencoder.h"

namespace EA
{
	namespace Types
	{
		BaseTypeReturn BaseTypeJsonParser::Parse(Factory* factory,
												 void* buffer, 
												 unsigned int size)
		{
			EA::RawString error(factory->GetAllocator());
			
			BaseTypeRef result = Parse(factory, buffer, size, error);
			
			EA_ASSERT_MESSAGE(result != NULL, error.c_str());
			
			return result;
		}
	
		BaseTypeReturn BaseTypeJsonParser::Parse(Factory* factory,
												 void* buffer, 
												 unsigned int size,
												 EA::RawString& error)
		{
			ArrayRef results = factory->Array();

			BaseTypeArrayEncoder encoder(results.GetUnsafePointer());

			JsonCallbackReader callbackReader(factory->GetAllocator());
			callbackReader.SetString(static_cast<char*>(buffer), size, false);

			JsonDecoderParams decoderParams(factory, &callbackReader);
			JsonDecoder<BaseTypeArrayEncoder>::Decode(&encoder, &decoderParams);

			BaseTypeRef data = NULL;

			data = (*results)[0];
			error.assign((*results)[1]->AsCStr());

			return data;
		}
	}
}
