/*
 * RankedNonlinearPattern.h
 *
 * Created on: Sep 27, 2017
 * Author: Jan Travnicek
 */

#pragma once

#include <tree/ranked/RankedNonlinearPattern.h>
#include <core/stringApi.hpp>

#include <tree/TreeFromStringLexer.h>

#include <tree/string/common/TreeFromStringParserCommon.h>
#include <tree/string/common/TreeToStringComposerCommon.h>

namespace core {

template<class SymbolType >
struct stringApi < tree::RankedNonlinearPattern < SymbolType > > {
	static tree::RankedNonlinearPattern < SymbolType > parse ( std::istream & input );
	static bool first ( std::istream & input );
	static void compose ( std::ostream & output, const tree::RankedNonlinearPattern < SymbolType > & tree );
};

template<class SymbolType >
tree::RankedNonlinearPattern < SymbolType > stringApi < tree::RankedNonlinearPattern < SymbolType > >::parse ( std::istream & input ) {
	tree::TreeFromStringLexer::Token token = tree::TreeFromStringLexer::next ( input );
	if ( token.type != tree::TreeFromStringLexer::TokenType::RANKED_NONLINEAR_PATTERN )
		throw exception::CommonException ( "Unrecognised RANKED_NONLINEAR_PATTERN token." );

	ext::set < common::ranked_symbol < SymbolType > > nonlinearVariables;
	bool isPattern = false;

	ext::tree < common::ranked_symbol < SymbolType > > content = tree::TreeFromStringParserCommon::parseRankedContent < SymbolType > ( input, isPattern, nonlinearVariables );
	if ( ! isPattern && nonlinearVariables.empty ( ) )
		throw exception::CommonException ( "Invalid input" );

	return tree::RankedNonlinearPattern < SymbolType > ( alphabet::WildcardSymbol::instance < common::ranked_symbol < SymbolType > > ( ), nonlinearVariables, content );
}

template<class SymbolType >
bool stringApi < tree::RankedNonlinearPattern < SymbolType > >::first ( std::istream & input ) {
	tree::TreeFromStringLexer::Token token = tree::TreeFromStringLexer::next ( input );
	bool res = token.type == tree::TreeFromStringLexer::TokenType::RANKED_NONLINEAR_PATTERN;
	tree::TreeFromStringLexer::putback ( input, token );
	return res;
}

template<class SymbolType >
void stringApi < tree::RankedNonlinearPattern < SymbolType > >::compose ( std::ostream &, const tree::RankedNonlinearPattern < SymbolType > & ) {
	throw exception::CommonException ( "Unimplemented." );
}

} /* namespace core */

