/*
 * Optional.h
 *
 * Created on: Apr 1, 2013
 * Author: Jan Travnicek
 */

#ifndef _XML_OBJECTS_OPTIONAL_H_
#define _XML_OBJECTS_OPTIONAL_H_

#include <alib/optional>
#include <exception/CommonException.h>
#include <core/xmlApi.hpp>

namespace core {

template < typename T >
struct xmlApi < ext::optional < T > > {
	static ext::optional < T > parse ( ext::deque < sax::Token >::iterator & input );
	static bool first ( const ext::deque < sax::Token >::const_iterator & input );
	static std::string xmlTagName ( );
	static void compose ( ext::deque < sax::Token > & output, const ext::optional < T > & input );
};

template < typename T >
ext::optional < T > xmlApi < ext::optional < T > >::parse ( ext::deque < sax::Token >::iterator & input ) {
	if ( sax::FromXMLParserHelper::isToken ( input, sax::Token::TokenType::START_ELEMENT, "void" ) ) {
		++input;
		sax::FromXMLParserHelper::popToken ( input, sax::Token::TokenType::END_ELEMENT, "void" );
		return ext::optional < T > ( );
	} else {
		return ext::optional < T > ( core::xmlApi < T >::parse ( input ) );
	}
}

template < typename T >
bool xmlApi < ext::optional < T > >::first ( const ext::deque < sax::Token >::const_iterator & input ) {
	return sax::FromXMLParserHelper::isToken ( input, sax::Token::TokenType::START_ELEMENT, "void" ) || xmlApi < T >::first ( input );
}

template < typename T >
std::string xmlApi < ext::optional < T > >::xmlTagName ( ) {
	throw exception::CommonException ( "Optional does not have xmlTagName." );
}

template < typename T >
void xmlApi < ext::optional < T > >::compose ( ext::deque < sax::Token > & output, const ext::optional < T > & input ) {
	if ( ! input ) {
		output.emplace_back("void", sax::Token::TokenType::START_ELEMENT);
		output.emplace_back("void", sax::Token::TokenType::END_ELEMENT);
	} else {
		core::xmlApi < T >::compose ( output, input.value ( ) );
	}
}

} /* namespace core */

#endif /* _XML_OBJECTS_OPTIONAL_H_ */
