/*
 * PostfixExpression.cpp
 *
 *  Created on: Dec 5, 2012
 *      Author: attero
 */

#include "PostfixExpression.h"

PostfixExpression::PostfixExpression(std::string name, ContextManager * context_manager):
	 name(name), operation("call"), context_manager(context_manager)
{
		type= "PostfixExpression";
		access_index_expr = nullptr;
}

PostfixExpression::PostfixExpression(std::string name, ContextManager * context_manager, ASTExpression * access_index_expr):
	 name(name),  operation("access"), context_manager(context_manager), access_index_expr(access_index_expr)
{
		type= "PostfixExpression";
}

PostfixExpression::~PostfixExpression() {
	for(auto i = arguments.begin(); i != arguments.end();)
	{
		delete *i;
		i = arguments.erase(i);
	}
}


void PostfixExpression::add_argument(ASTExpression * expression)
{
	arguments.push_back(expression);
}


SenchaObject PostfixExpression::evaluate()
{
	return execute();
}

SenchaObject PostfixExpression::execute() {
	SenchaObject result = SenchaObject();
	if(operation == "call")
		return context_manager->execute_function(name, arguments);
	else if(operation == "access")
	{
		SenchaObject called_value = context_manager->get_top()->get(name);
		SenchaObject access_index = access_index_expr->execute();
		if(access_index.type == SenchaObject::integer_number)
		{
			if(called_value.type == SenchaObject::string_literal)
			{
				called_value = context_manager->get_top()->get_updated_string(name);
				SenchaArray array(name, context_manager, called_value.text);
				return  array.get(access_index.integer);
			}
			else
			{
				SenchaArray array(name, context_manager);
				return array.get(access_index.integer);
			}
		}
	}
	result.type = SenchaObject::invalid;
	return result;

}


