/*
 * NaryOperationAbstraction.hpp
 *
 *  Created on: 20. 8. 2017
 *	  Author: Jan Travnicek
 */

#ifndef _NARY_OPERATION_ABSTRACTION_HPP_
#define _NARY_OPERATION_ABSTRACTION_HPP_

#include <alib/memory>
#include <alib/array>

#include <abstraction/OperationAbstraction.hpp>
#include <common/AbstractionHelpers.hpp>

namespace abstraction {

template < size_t NumberOfParams >
class NaryOperationAbstractionImpl : virtual public OperationAbstraction {
	ext::array < std::pair < std::shared_ptr < abstraction::Value >, bool >, NumberOfParams > m_params;

protected:
	ext::array < std::pair < std::shared_ptr < abstraction::Value >, bool >, NumberOfParams > & getParams ( ) {
		return m_params;
	}

	virtual std::shared_ptr < abstraction::Value > run ( ) = 0;

private:
	void attachInput ( const std::shared_ptr < abstraction::Value > & input, size_t index, bool move ) override {
		if ( index >= m_params.size ( ) )
			throw std::invalid_argument ( "Parameter index " + ext::to_string ( index ) + " out of bounds.");

		m_params [ index ].first = input;
		m_params [ index ].second = move;
	}

	void detachInput ( size_t index ) override {
		if ( index >= m_params.size ( ) )
			throw std::invalid_argument ( "Parameter index " + ext::to_string ( index ) + " out of bounds.");

		m_params [ index ].first = nullptr;
		m_params [ index ].second = false;
	}

public:
	NaryOperationAbstractionImpl ( ) {
		for ( size_t i = 0; i < NumberOfParams; ++ i ) {
			m_params [ i ].first = nullptr;
			m_params [ i ].second = false;
		}
	}

	bool inputsAttached ( ) const override {
		for ( const std::pair < std::shared_ptr < abstraction::Value >, bool > & param : m_params )
			if ( ! param.first )
				return false;

		return true;
	}

	std::shared_ptr < abstraction::Value > eval ( ) override {
		if ( ! inputsAttached ( ) )
			return nullptr;

		return this->run ( );
	}

	size_t numberOfParams ( ) const override {
		return NumberOfParams;
	}

};

} /* namespace abstraction */

extern template class abstraction::NaryOperationAbstractionImpl < 0 >;
extern template class abstraction::NaryOperationAbstractionImpl < 1 >;
extern template class abstraction::NaryOperationAbstractionImpl < 2 >;
extern template class abstraction::NaryOperationAbstractionImpl < 3 >;

namespace abstraction {

template < class ... ParamTypes >
class NaryOperationAbstraction : virtual public NaryOperationAbstractionImpl < sizeof ... ( ParamTypes ) > {
public:
	ext::type_index getParamTypeIndex ( size_t index ) const override {
		return abstraction::paramType < ParamTypes ... > ( index );
	}

	ext::set < abstraction::ParamQualifiers::ParamQualifier > getParamTypeQualifiers ( size_t index ) const override {
		return abstraction::paramTypeQualifiers < ParamTypes ... > ( index );
	}

};

} /* namespace abstraction */

#endif /* _NARY_OPERATION_ABSTRACTION_HPP_ */
