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

#include "BasicExpression.h"

void BasicExpression::set_operator(std::string op)
{
	this->oper = op;
}

void BasicExpression::set_left_operand(ASTNode * left)
{
	if(!this->children_set)
	{
		children.push_back(left);
	}
	else
	{
		this->children[0] = left;
	}

	if(children.size() == 2)
		children_set = true;
}

void BasicExpression::set_right_operand(ASTNode * right)
{
	if(!this->children_set)
		{
			children.push_back(right);

		}
		else
		{
			this->children[1] = right;
		}

		if(children.size() == 2)
			children_set = true;
}
void BasicExpression::execute()
{
	//children[0]->execute();
	//children[1]->execute();
	std::cout << evaluate().repr() << std::endl;
}

void BasicExpression::execute_quietly()
{
	evaluate();
}
SenchaObject BasicExpression::evaluate()
{
	//TODO refactor it ;)

	SenchaObject left = static_cast<ASTExpression *>(children[0])->evaluate();
	SenchaObject right = static_cast<ASTExpression *>(children[1])->evaluate();


	SenchaObject so;
	if(oper == "+")
	{
		so = SenchaObject(left + right);
	}
	else if(oper == "-")
	{
		so = SenchaObject(left - right);
	}
	else if(oper == "*")
	{
		so = SenchaObject(left * right);
	}
	else if(oper == "/")
	{
		so = SenchaObject(left / right);
	}
	else if(oper == "=")
	{
		so = SenchaObject(right);
	}
	return so;
}

BasicExpression::BasicExpression(ASTNode * parent) {
	this->parent = parent;
	children_set = false;
}

BasicExpression::~BasicExpression() {
	// TODO Auto-generated destructor stub
	// TODO free children memory
}


std::string BasicExpression::debug()
{
	std::string debug_note = "Basic expression:\n";
	debug_note += "left operand: \n";
	debug_note += this->children[0]->debug();
	debug_note += "\nright operand:\n" + this->children[1]->debug();
	debug_note += "\nOperator: " + this->oper +"\n###\n";
	return debug_note;
}
