/*
 * BorderArray.cpp
 *
 *  Created on: 4. 10. 2019
 *      Author: Tomas Pecka, Jan Travnicek
 */

#ifndef _ARBOLOGY_BORDER_ARRAY_H_
#define _ARBOLOGY_BORDER_ARRAY_H_

#include <cstdlib>

#include <alib/vector>

#include <global/GlobalData.h>

#include "SubtreeJumpTable.h"

#include <tree/ranked/PrefixRankedBarNonlinearPattern.h>
#include <tree/ranked/PrefixRankedBarPattern.h>
#include <tree/ranked/PrefixRankedNonlinearPattern.h>
#include <tree/ranked/PrefixRankedPattern.h>

namespace tree::properties {

class BorderArray {

public:
	template < class PrefixRankedPatternType >
	static ext::vector < size_t > construct ( const PrefixRankedPatternType & pattern );
};

template < class PrefixRankedPatternType >
ext::vector < size_t > BorderArray::construct ( const PrefixRankedPatternType & pattern ) {
	ext::vector < int > subtreeJumpTable = SubtreeJumpTable::compute ( pattern );
	ext::vector < size_t > res ( pattern.getContent ( ).size ( ) + 1, 0 );
	ext::vector < unsigned > mins ( pattern.getContent ( ).size ( ) + 1 );
	for ( unsigned i = 0; i <= pattern.getContent ( ) .size ( ); i++ )
		mins [ i ] = i + 1;
	res [ 0 ] = -1;

	for ( unsigned ofs = 1; ofs < pattern.getContent ( ).size ( ); ofs++ ) {

		unsigned i = 0;   // index do patternu
		unsigned j = ofs; // index do factoru

		while ( 1 ) {
			if ( i >= pattern.getContent ( ).size ( ) ) {
				while ( j < pattern.getContent ( ).size ( ) ) {
					mins [ j ] = std::min ( mins [ j ], ofs );
					j++;
				}
				break;
			} else if ( j >= pattern.getContent ( ).size ( ) ) {
				break;
			} else if ( pattern.getContent ( )[ i ] == pattern.getContent ( )[ j ] ) {
				mins [ j ] = std::min ( mins [ j ], ofs );;
				i++;
				j++;
			} else if ( pattern.getContent ( )[ i ] == pattern.getSubtreeWildcard ( ) || pattern.getContent ( )[ j ] == pattern.getSubtreeWildcard ( ) ) {
				for ( int k = ( int ) j; k < subtreeJumpTable [ j ] ; k++ )
					mins [ k ] = std::min ( mins [ k ], ofs );;

				i = subtreeJumpTable[ i ];
				j = subtreeJumpTable[ j ];
			} else {
				break;
			}
		}
	}

	// std::cout << mins << std::endl;

	res [ 1 ] = 0;
	for ( size_t i = 2; i <= pattern.getContent ( ).size ( ); i++ ) {
		res [ i ] = i - mins [ i - 1 ];
	}

	return res;
}

} /* namespace tree::properties */

#endif /* _ARBOLOGY_BORDER_ARRAY_H_ */
