/*
 * PrefixRankedPattern.h
 *
 * This file is part of Algorithms library toolkit.
 * Copyright (C) 2017 Jan Travnicek (jan.travnicek@fit.cvut.cz)

 * Algorithms library toolkit is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * Algorithms library toolkit is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with Algorithms library toolkit.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  Created on: Nov 23, 2013
 *      Author: Jan Travnicek
 */

#pragma once

#include <common/DefaultSymbolType.h>

namespace tree {

template < class SymbolType = DefaultSymbolType >
class PrefixRankedPattern;

} /* namespace tree */

#include <sstream>

#include <alib/set>
#include <alib/vector>
#include <alib/tree>
#include <alib/algorithm>
#include <alib/deque>

#include <core/components.hpp>
#include <common/ranked_symbol.hpp>

#include <tree/TreeException.h>
#include <tree/common/TreeAuxiliary.h>

#include <alphabet/WildcardSymbol.h>

#include <core/normalize.hpp>
#include <tree/common/TreeNormalize.h>

#include <string/LinearString.h>

#include "RankedPattern.h"
#include "PrefixRankedTree.h"

namespace tree {

class GeneralAlphabet;
class SubtreeWildcard;

/**
 * \brief
 * Tree pattern represented as linear sequece as result of preorder traversal. The representation is so called ranked, therefore it consists of ranked symbols. The rank of the ranked symbol needs to be compatible with unsigned integer. Additionally the pattern contains a special wildcard symbol representing any subtree.
 *
 * \details
 * T = (A, C, W \in ( A \minus B ) ),
 * A (Alphabet) = finite set of ranked symbols,
 * C (Content) = linear representation of the pattern content
 * W (Wildcard) = special symbol representing any subtree
 *
 * \tparam SymbolType used for the symbol part of the ranked symbol
 */
template < class SymbolType >
class PrefixRankedPattern final : public core::Components < PrefixRankedPattern < SymbolType >, ext::set < common::ranked_symbol < SymbolType > >, component::Set, GeneralAlphabet, common::ranked_symbol < SymbolType >, component::Value, SubtreeWildcard > {
	/**
	 * Linear representation of the pattern content.
	 */
	ext::vector < common::ranked_symbol < SymbolType > > m_Data;

	/**
	 * Checker of validity of the representation of the ettern
	 *
	 * \throws TreeException when new pattern representation is not valid
	 */
	void arityChecksum ( const ext::vector < common::ranked_symbol < SymbolType > > & data );

public:
	/**
	 * \brief Creates a new instance of the pattern with concrete alphabet, content, and wildcard.
	 *
	 * \param subtreeWildcard the wildcard symbol
	 * \param alphabet the initial alphabet of the pattern
	 * \param data the initial pattern in linear representation
	 */
	explicit PrefixRankedPattern ( common::ranked_symbol < SymbolType > subtreeWildcard, ext::set < common::ranked_symbol < SymbolType > > alphabet, ext::vector < common::ranked_symbol < SymbolType > > data );

	/**
	 * \brief Creates a new instance of the pattern with concrete content and wildcard. The alphabet is deduced from the content.
	 *
	 * \param subtreeWildcard the wildcard symbol
	 * \param data the initial pattern in linear representation
	 */
	explicit PrefixRankedPattern ( common::ranked_symbol < SymbolType > subtreeWildcard, ext::vector < common::ranked_symbol < SymbolType > > data );

	/**
	 * \brief Creates a new instance of the pattern based on the PrefixRankedTree. The linear representation is copied from tree. Alphabet as well. Subtree wildcard is defaultly constructed.
	 *
	 * \param tree representation of a tree.
	 */
	explicit PrefixRankedPattern ( const PrefixRankedTree < SymbolType > & tree );

	/**
	 * \brief Creates a new instance of the pattern based on the RankedPattern. The linear representation is constructed by preorder traversal on the tree parameter.
	 *
	 * \param tree representation of a pattern.
	 */
	explicit PrefixRankedPattern ( const RankedPattern < SymbolType > & tree );

	/**
	 * Getter of the alphabet.
	 *
	 * \returns the alphabet of the pattern
	 */
	const ext::set < common::ranked_symbol < SymbolType > > & getAlphabet ( ) const & {
		return this->template accessComponent < GeneralAlphabet > ( ).get ( );
	}

	/**
	 * Getter of the alphabet.
	 *
	 * \returns the alphabet of the pattern
	 */
	ext::set < common::ranked_symbol < SymbolType > > && getAlphabet ( ) && {
		return std::move ( this->template accessComponent < GeneralAlphabet > ( ).get ( ) );
	}

	/**
	 * Adder of an alphabet symbols.
	 *
	 * \param symbols the new symbols to be added to the alphabet
	 */
	void extendAlphabet ( const ext::set < common::ranked_symbol < SymbolType > > & symbols ) {
		this->template accessComponent < GeneralAlphabet > ( ).add ( symbols );
	}

	/**
	 * Getter of the wildcard symbol.
	 *
	 * \returns the wildcard symbol of the pattern
	 */
	const common::ranked_symbol < SymbolType > & getSubtreeWildcard ( ) const & {
		return this->template accessComponent < SubtreeWildcard > ( ).get ( );
	}

	/**
	 * Getter of the wildcard symbol.
	 *
	 * \returns the wildcard symbol of the pattern
	 */
	common::ranked_symbol < SymbolType > && getSubtreeWildcard ( ) && {
		return std::move ( this->template accessComponent < SubtreeWildcard > ( ).get ( ) );
	}

	/**
	 * Getter of the pattern representation.
	 *
	 * \return List of symbols forming the linear representation of the pattern.
	 */
	const ext::vector < common::ranked_symbol < SymbolType > > & getContent ( ) const &;

	/**
	 * Getter of the pattern representation.
	 *
	 * \return List of symbols forming the linear representation of the pattern.
	 */
	ext::vector < common::ranked_symbol < SymbolType > > && getContent ( ) &&;

	/**
	 * Setter of the representation of the pattern.
	 *
	 * \throws TreeException when new pattern representation is not valid or when symbol of the representation are not present in the alphabet
	 *
	 * \param data new List of symbols forming the representation of the pattern.
	 */
	void setContent ( ext::vector < common::ranked_symbol < SymbolType > > data );

	/**
	 * @return true if pattern is an empty word (vector length is 0). The method is present to allow compatibility with strings. Tree is never empty in this datatype.
	 */
	bool isEmpty ( ) const;

	/**
	 * The three way comparison implementation
	 *
	 * \param other the other instance
	 *
	 * \returns the ordering between this object and the @p other.
	 */
	auto operator <=> ( const PrefixRankedPattern & other ) const {
		return std::tie ( m_Data, getAlphabet ( ), getSubtreeWildcard ( ) ) <=> std::tie ( other.m_Data, other.getAlphabet ( ), other.getSubtreeWildcard ( ) );
	}

	/**
	 * The equality comparison implementation.
	 *
	 * \param other the other object to compare with.
	 *
	 * \returns true if this and other objects are equal, false othervise
	 */
	bool operator == ( const PrefixRankedPattern & other ) const {
		return std::tie ( m_Data, getAlphabet ( ), getSubtreeWildcard ( ) ) == std::tie ( other.m_Data, other.getAlphabet ( ), other.getSubtreeWildcard ( ) );
	}

	/**
	 * Print this object as raw representation to ostream.
	 *
	 * \param out ostream where to print
	 * \param instance object to print
	 *
	 * \returns modified output stream
	 */
	friend std::ostream & operator << ( std::ostream & out, const PrefixRankedPattern & instance ) {
		out << "(PrefixRankedPattern ";
		out << "alphabet = " << instance.getAlphabet ( );
		out << "content = " << instance.getContent ( );
		out << "subtreeWildcard = " << instance.getSubtreeWildcard ( );
		out << ")";
		return out;
	}

	/**
	 * Casts this instance to as compact as possible string representation.
	 *
	 * \returns string representation of the object
	 */
	explicit operator std::string ( ) const;

	/**
	 * \brief Creates a new instance of the string from a linear representation of a tree
	 *
	 * \returns tree casted to string
	 */
	explicit operator string::LinearString < common::ranked_symbol < SymbolType > > ( ) const {
		return string::LinearString < common::ranked_symbol < SymbolType > > ( getAlphabet ( ), getContent ( ) );
	}
};

template < class SymbolType >
PrefixRankedPattern < SymbolType >::PrefixRankedPattern ( common::ranked_symbol < SymbolType > subtreeWildcard, ext::set < common::ranked_symbol < SymbolType > > alphabet, ext::vector < common::ranked_symbol < SymbolType > > data ) : core::Components < PrefixRankedPattern, ext::set < common::ranked_symbol < SymbolType > >, component::Set, GeneralAlphabet, common::ranked_symbol < SymbolType >, component::Value, SubtreeWildcard > ( std::move ( alphabet ), std::move ( subtreeWildcard ) ) {
	setContent ( std::move ( data ) );
}

template < class SymbolType >
PrefixRankedPattern < SymbolType >::PrefixRankedPattern ( common::ranked_symbol < SymbolType > subtreeWildcard, ext::vector < common::ranked_symbol < SymbolType > > data ) : PrefixRankedPattern ( subtreeWildcard, ext::set < common::ranked_symbol < SymbolType > > ( data.begin ( ), data.end ( ) ) + ext::set < common::ranked_symbol < SymbolType > > { subtreeWildcard }, data ) {
}

template < class SymbolType >
PrefixRankedPattern < SymbolType >::PrefixRankedPattern ( const PrefixRankedTree < SymbolType > & tree ) : PrefixRankedPattern ( alphabet::WildcardSymbol::instance < common::ranked_symbol < SymbolType > > ( ), tree.getAlphabet ( ) + ext::set < common::ranked_symbol < SymbolType > > { alphabet::WildcardSymbol::instance < common::ranked_symbol < SymbolType > > ( ) }, tree.getContent ( ) ) {
}

template < class SymbolType >
PrefixRankedPattern < SymbolType >::PrefixRankedPattern ( const RankedPattern < SymbolType > & tree ) : PrefixRankedPattern ( tree.getSubtreeWildcard ( ), tree.getAlphabet ( ), TreeAuxiliary::treeToPrefix ( tree.getContent ( ) ) ) {
}

template < class SymbolType >
const ext::vector < common::ranked_symbol < SymbolType > > & PrefixRankedPattern < SymbolType >::getContent ( ) const & {
	return this->m_Data;
}

template < class SymbolType >
ext::vector < common::ranked_symbol < SymbolType > > && PrefixRankedPattern < SymbolType >::getContent ( ) && {
	return std::move ( this->m_Data );
}

template < class SymbolType >
void PrefixRankedPattern < SymbolType >::setContent ( ext::vector < common::ranked_symbol < SymbolType > > data ) {
	arityChecksum ( data );

	ext::set < common::ranked_symbol < SymbolType > > minimalAlphabet ( data.begin ( ), data.end ( ) );
	ext::set < common::ranked_symbol < SymbolType > > unknownSymbols;
	std::set_difference ( minimalAlphabet.begin ( ), minimalAlphabet.end ( ), getAlphabet().begin ( ), getAlphabet().end ( ), std::inserter ( unknownSymbols, unknownSymbols.end ( ) ) );

	if ( !unknownSymbols.empty ( ) )
		throw TreeException ( "Input symbols not in the alphabet." );

	this->m_Data = std::move ( data );
}

template < class SymbolType >
void PrefixRankedPattern < SymbolType >::arityChecksum ( const ext::vector < common::ranked_symbol < SymbolType > > & data ) {
	int arityChecksumAcc = 1;

	for ( const common::ranked_symbol < SymbolType > & symbol : data ) {
		arityChecksumAcc += ( unsigned ) symbol.getRank ( );
		arityChecksumAcc -= 1;
	}

	if ( arityChecksumAcc != 0 ) throw TreeException ( "The string does not form a tree" );
}

template < class SymbolType >
bool PrefixRankedPattern < SymbolType >::isEmpty ( ) const {
	return this->m_Data.empty ( );
}

template < class SymbolType >
PrefixRankedPattern < SymbolType >::operator std::string ( ) const {
	std::stringstream ss;
	ss << "\"";

	for ( const common::ranked_symbol < SymbolType > & symbol : this->m_Data )
		ss << symbol;

	ss << "\"";
	return std::move ( ss ).str ( );
}

} /* namespace tree */

namespace core {

/**
 * Helper class specifying constraints for the pattern's internal alphabet component.
 *
 * \tparam SymbolType used for the symbol part of the ranked symbols of the alphabet of the pattern.
 */
template < class SymbolType >
class SetConstraint< tree::PrefixRankedPattern < SymbolType >, common::ranked_symbol < SymbolType >, tree::GeneralAlphabet > {
public:
	/**
	 * Returns true if the symbol is still used in the pattern.
	 *
	 * \param pattern the tested pattern
	 * \param symbol the tested symbol
	 *
	 * \returns true if the symbol is used, false othervise
	 */
	static bool used ( const tree::PrefixRankedPattern < SymbolType > & pattern, const common::ranked_symbol < SymbolType > & symbol ) {
		const ext::vector < common::ranked_symbol < SymbolType > > & content = pattern.getContent ( );

		return std::find ( content.begin ( ), content.end ( ), symbol ) != content.end ( ) || pattern.template accessComponent < tree::SubtreeWildcard > ( ).get ( ) == symbol;
	}

	/**
	 * Returns true as all symbols are possibly available to be in an alphabet.
	 *
	 * \param pattern the tested pattern
	 * \param symbol the tested symbol
	 *
	 * \returns true
	 */
	static bool available ( const tree::PrefixRankedPattern < SymbolType > &, const common::ranked_symbol < SymbolType > & ) {
		return true;
	}

	/**
	 * All symbols are valid as symbols of an alphabet.
	 *
	 * \param pattern the tested pattern
	 * \param symbol the tested symbol
	 */
	static void valid ( const tree::PrefixRankedPattern < SymbolType > &, const common::ranked_symbol < SymbolType > & ) {
	}
};

/**
 * Helper class specifying constraints for the pattern's internal subtree wildcard element.
 *
 * \tparam SymbolType used for the symbol part of the ranked symbols of the alphabet of the pattern.
 */
template < class SymbolType >
class ElementConstraint< tree::PrefixRankedPattern < SymbolType >, common::ranked_symbol < SymbolType >, tree::SubtreeWildcard > {
public:
	/**
	 * Determines whether the symbol is available in the pattern's alphabet.
	 *
	 * \param pattern the tested pattern
	 * \param symbol the tested symbol
	 *
	 * \returns true if the symbol is already in the alphabet of the pattern
	 */
	static bool available ( const tree::PrefixRankedPattern < SymbolType > & pattern, const common::ranked_symbol < SymbolType > & symbol ) {
		return pattern.template accessComponent < tree::GeneralAlphabet > ( ).get ( ).count ( symbol );
	}

	/**
	 * Subtree wildcard needs to have zero arity.
	 *
	 * \param pattern the tested pattern
	 * \param symbol the tested symbol
	 *
	 * \throws TreeException if the symbol does not have zero arity
	 */
	static void valid ( const tree::PrefixRankedPattern < SymbolType > &, const common::ranked_symbol < SymbolType > & symbol) {
		if( ( unsigned ) symbol.getRank() != 0 )
			throw tree::TreeException ( "SubtreeWildcard symbol has nonzero arity" );
	}
};

/**
 * Helper for normalisation of types specified by templates used as internal datatypes of symbols.
 *
 * \returns new instance of the tree with default template parameters or unmodified instance if the template parameters were already default ones
 */
template < class SymbolType >
struct normalize < tree::PrefixRankedPattern < SymbolType > > {
	static tree::PrefixRankedPattern < > eval ( tree::PrefixRankedPattern < SymbolType > && value ) {
		common::ranked_symbol < DefaultSymbolType > wildcard = alphabet::SymbolNormalize::normalizeRankedSymbol ( std::move ( value ).getSubtreeWildcard ( ) );
		ext::set < common::ranked_symbol < DefaultSymbolType > > alphabet = alphabet::SymbolNormalize::normalizeRankedAlphabet ( std::move ( value ).getAlphabet ( ) );
		ext::vector < common::ranked_symbol < DefaultSymbolType > > content = alphabet::SymbolNormalize::normalizeRankedSymbols ( std::move ( value ).getContent ( ) );

		return tree::PrefixRankedPattern < > ( std::move ( wildcard ), std::move ( alphabet ), std::move ( content ) );
	}
};

} /* namespace core */

extern template class tree::PrefixRankedPattern < >;

