#ifndef _CLI_IF_COMMAND_H_
#define _CLI_IF_COMMAND_H_

#include <ast/Command.h>
#include <environment/Environment.h>
#include <ast/Statement.h>
#include <common/CastHelper.h>

namespace cli {

class IfCommand : public Command {
	std::unique_ptr < Expression > m_condition;
	std::unique_ptr < Command > m_thenBranch;
	std::unique_ptr < Command > m_elseBranch;

public:
	IfCommand ( std::unique_ptr < Expression > condition, std::unique_ptr < Command > thenBranch, std::unique_ptr < Command > elseBranch ) : m_condition ( std::move ( condition ) ), m_thenBranch ( std::move ( thenBranch ) ), m_elseBranch ( std::move ( elseBranch ) ) {
	}

	CommandResult run ( Environment & environment ) const override {
		std::shared_ptr < abstraction::Value > conditionResult = m_condition->translateAndEval ( environment );

		std::shared_ptr < abstraction::Value > castedResult = abstraction::CastHelper::eval ( environment, conditionResult, "bool" );

		if ( std::static_pointer_cast < abstraction::ValueHolderInterface < bool > > ( castedResult )->getValue ( ) )
			return m_thenBranch->run ( environment );
		else if ( m_elseBranch != nullptr )
			return m_elseBranch->run ( environment );

		return cli::CommandResult::OK;
	}
};

} /* namespace cli */

#endif /* _CLI_IF_COMMAND_H_ */
