/*
 * Context.cpp
 *
 *  Created on: Dec 7, 2012
 *      Author: attero
 */

#include "ContextManager.h"

ContextManager::ContextManager() {
	contexts["global"] = new Context("global");
	stack.push(contexts["global"]);
	index = 0;
}

ContextManager::~ContextManager() {
}

Context * ContextManager::create_new_context()
{
	Context * context = new Context("abcd" + to_string(index));
	index++;
	contexts[context->name] = context;
	stack.push(context);
	return context;
}

SenchaObject ContextManager::execute_function(std::string name, std::vector<ASTExpression *> arguments)
{
	SenchaObject result;
	if(contexts["global"]->contains_nfunction(name))
	{
		result = contexts["global"]->registered_functions[name](arguments);
	}

	else if(contexts["global"]->contains_sfunction(name))
	{
		std::vector<SenchaObject> evaluated_arguments;
		for(auto argument : arguments)
			evaluated_arguments.push_back((argument->evaluate()));

		SenchaFunction * function = contexts["global"]->registered_sfunctions[name];
		std::string name_of_context = create_new_context()->name;
		if( arguments.size() != function->names_of_arguments.size())
		{
			result.type = SenchaObject::invalid;
			return result;
		}
		for(unsigned int i = 0; i < function->names_of_arguments.size(); i++)
		{
			//std::cout << "I'm adding to context " + get_top()->name + " variable of name: " +  function->names_of_arguments[i];
			//std::cout << "Which should be equal " + evaluated_arguments[i].repr() << std::endl;
			get_top()->add(function->names_of_arguments[i], evaluated_arguments[i]);
		}

		result = (*function)();
		pop_context();
		destroy_context(name_of_context);
	}
	return result;

}

Context * ContextManager::get_top()
{
	return stack.top();
}

void ContextManager::pop_context()
{
	stack.pop();
}

Context * ContextManager::context(std::string name)
{
	if(contexts.count(name) != 0) return contexts[name];
	else return nullptr;
}

void ContextManager::destroy_context(std::string name)
{
	auto iter = contexts.find(name);
	if(iter != contexts.end())
	{
		delete ((*iter).second);
		contexts.erase(iter);
	}
}
