/*
 * FromXMLParserHelper.cpp
 *
 *  Created on: Oct 12, 2013
 *      Author: Jan Travnicek
 */

#include "FromXMLParserHelper.h"
#include "ParserException.h"
#include <exception/CommonException.h>
#include "SaxParseInterface.h"

namespace sax {

void FromXMLParserHelper::skipAttributes ( ext::deque < Token >::const_iterator & input, Token::TokenType type ) {
	if ( type == sax::Token::TokenType::START_ELEMENT || type == sax::Token::TokenType::END_ELEMENT || type == sax::Token::TokenType::CHARACTER ) {
		while ( input->getType ( ) == sax::Token::TokenType::START_ATTRIBUTE ) {
			input += 3; /* skip START, PAYLOAD, END */
		}
	}
}

void FromXMLParserHelper::skipAttributes ( ext::deque < Token >::iterator & input, Token::TokenType type ) {
	if ( type == sax::Token::TokenType::START_ELEMENT || type == sax::Token::TokenType::END_ELEMENT || type == sax::Token::TokenType::CHARACTER ) {
		while ( input->getType ( ) == sax::Token::TokenType::START_ATTRIBUTE ) {
			input += 3; /* skip START, PAYLOAD, END */
		}
	}
}

bool FromXMLParserHelper::isToken(ext::deque<Token>::const_iterator input, Token::TokenType type, const std::string& data) {
	skipAttributes ( input, type );
	return input->getType() == type && input->getData() == data;
}

bool FromXMLParserHelper::isTokenType(ext::deque<Token>::const_iterator input, Token::TokenType type) {
	skipAttributes ( input, type );
	return input->getType() == type;
}

void FromXMLParserHelper::popToken(ext::deque<Token>::iterator& input, Token::TokenType type, const std::string& data) {
	if (isToken(input, type, data)) {
		skipAttributes ( input, type );
		++input;
	} else {
		throw ParserException(Token(data, type), *input);
	}
}

std::string FromXMLParserHelper::popTokenData(ext::deque<Token>::iterator& input, Token::TokenType type) {
	if(isTokenType(input, type)) {
		skipAttributes ( input, type );
		return std::move ( * input ++ ).getData ( );
	} else {
		throw ParserException(Token("?", type), *input);
	}
}

std::string FromXMLParserHelper::getTokenData(ext::deque<Token>::const_iterator input, Token::TokenType type) {
	if(isTokenType(input, type)) {
		skipAttributes ( input, type );
		return input->getData();
	} else {
		throw ParserException(Token("?", type), *input);
	}
}

} /* namespace sax */
